Image positioning in Listview search - Java for Android App Development

I have a problem with the pictures when I use the search then the app always takes the first picture instead of the picture that belongs.
I added two pictures where you can see what I mean by "Adrenaline".
Can someone help me by chance?
I would be very happy.
Sorry for my bad English.
Code:
package com.0000.00000;
import androidx.appcompat.app.AppCompatActivity;
import android.app.*;
import android.os.*;
import android.view.*;
import android.view.View.*;
import android.widget.*;
import android.content.*;
import android.graphics.*;
import android.media.*;
import android.net.*;
import android.text.*;
import android.util.*;
import android.webkit.*;
import android.animation.*;
import android.view.animation.*;
import java.util.*;
import java.text.*;
import java.util.HashMap;
import java.util.ArrayList;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.AdRequest;
import android.widget.ListView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.AdListener;
import android.content.Intent;
import android.net.Uri;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.AdapterView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class PerksActivity extends Activity {
private ArrayList<Integer> image_list = new ArrayList<>();
private HashMap<String, Object> map_var = new HashMap<>();
private String saved = "";
private double length = 0;
private double r = 0;
private String value1 = "";
private String value2 = "";
private String value3 = "";
private String value4 = "";
private ArrayList<HashMap<String, Object>> map_list = new ArrayList<>();
private LinearLayout linear1;
private LinearLayout linear2;
private LinearLayout linear3;
private LinearLayout linear10;
private LinearLayout linear11;
private LinearLayout linear12;
private TextView textview4;
private AdView adview1;
private LinearLayout linear15;
private LinearLayout linear16;
private LinearLayout linear44;
private ListView listview1;
private EditText edittext1;
private LinearLayout linear929;
private TextView textview8;
private InterstitialAd admob;
private AdListener _admob_ad_listener;
private Intent page_intent = new Intent();
private AlertDialog.Builder popup;
@Override
protected void onCreate(Bundle _savedInstanceState) {
super.onCreate(_savedInstanceState);
setContentView(R.layout.perks);
initialize(_savedInstanceState);
initializeLogic();
}
private void initialize(Bundle _savedInstanceState) {
linear1 = (LinearLayout) findViewById(R.id.linear1);
linear2 = (LinearLayout) findViewById(R.id.linear2);
linear3 = (LinearLayout) findViewById(R.id.linear3);
linear10 = (LinearLayout) findViewById(R.id.linear10);
linear11 = (LinearLayout) findViewById(R.id.linear11);
linear12 = (LinearLayout) findViewById(R.id.linear12);
textview4 = (TextView) findViewById(R.id.textview4);
adview1 = (AdView) findViewById(R.id.adview1);
linear15 = (LinearLayout) findViewById(R.id.linear15);
linear16 = (LinearLayout) findViewById(R.id.linear16);
linear44 = (LinearLayout) findViewById(R.id.linear44);
listview1 = (ListView) findViewById(R.id.listview1);
edittext1 = (EditText) findViewById(R.id.edittext1);
linear929 = (LinearLayout) findViewById(R.id.linear929);
textview8 = (TextView) findViewById(R.id.textview8);
popup = new AlertDialog.Builder(this);
listview1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> _param1, View _param2, int _param3, long _param4) {
final int _position = _param3;
if (_position == 0) {
popup.setTitle(map_list.get((int)_position).get("d").toString());
popup.setMessage(map_list.get((int)_position).get("e").toString());
popup.setPositiveButton("Schliessen", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface _dialog, int _which) {
}
});
popup.create().show();
}
if (_position == 1) {
popup.setTitle(map_list.get((int)_position).get("d").toString());
popup.setMessage(map_list.get((int)_position).get("e").toString());
popup.setPositiveButton("Schliessen", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface _dialog, int _which) {
}
});
popup.create().show();
}
if (_position == 2) {
popup.setTitle(map_list.get((int)_position).get("d").toString());
popup.setMessage(map_list.get((int)_position).get("e").toString());
popup.setPositiveButton("Schliessen", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface _dialog, int _which) {
}
});
popup.create().show();
}
}
});
edittext1.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence _param1, int _param2, int _param3, int _param4) {
final String _charSeq = _param1.toString();
map_list = new Gson().fromJson(saved, new TypeToken<ArrayList<HashMap<String, Object>>>(){}.getType());
length = map_list.size();
r = length - 1;
for(int _repeat17 = 0; _repeat17 < (int)(length); _repeat17++) {
value1 = map_list.get((int)r).get("a").toString();
value2 = map_list.get((int)r).get("b").toString();
value3 = map_list.get((int)r).get("c").toString();
if (!(_charSeq.length() > value1.length()) && value1.toLowerCase().contains(_charSeq.toLowerCase())) {
}
else {
if (!(_charSeq.length() > value2.length()) && value2.toLowerCase().contains(_charSeq.toLowerCase())) {
}
else {
if (!(_charSeq.length() > value3.length()) && value3.toLowerCase().contains(_charSeq.toLowerCase())) {
}
else {
map_list.remove((int)(r));
}
}
}
r--;
}
listview1.setAdapter(new Listview1Adapter(map_list));
((BaseAdapter)listview1.getAdapter()).notifyDataSetChanged();
}
@Override
public void beforeTextChanged(CharSequence _param1, int _param2, int _param3, int _param4) {
}
@Override
public void afterTextChanged(Editable _param1) {
}
});
_admob_ad_listener = new AdListener() {
@Override
public void onAdLoaded() {
admob.show();
}
@Override
public void onAdFailedToLoad(int _param1) {
final int _errorCode = _param1;
SketchwareUtil.showMessage(getApplicationContext(), "Werbung konnte nicht Geladen werden!!!".concat(String.valueOf((long)(_errorCode))));
}
@Override
public void onAdOpened() {
}
@Override
public void onAdClosed() {
}
};
}
private void initializeLogic() {
adview1.loadAd(new AdRequest.Builder().addTestDevice("0815")
.build());
map_var = new HashMap<>();
map_var.put("a", getResources().getString(R.string.perksstriche));
map_var.put("b", getResources().getString(R.string.perksueberlebende));
map_var.put("c", getResources().getString(R.string.perksstriche02));
map_var.put("d", getResources().getString(R.string.perksinfopopupheadername));
map_var.put("e", getResources().getString(R.string.perksinfopopuptxtname));
map_list.add(map_var);
map_var = new HashMap<>();
map_var.put("a", getResources().getString(R.string.perkablenkungname));
map_var.put("b", getResources().getString(R.string.perksueberlebendenadamfrancisname));
map_var.put("c", getResources().getString(R.string.perkslehrbarimblutnetzlevel30name));
map_var.put("d", getResources().getString(R.string.perkablenkungpopupheadername));
map_var.put("e", getResources().getString(R.string.perkablenkungpopuptxt));
map_list.add(map_var);
map_var = new HashMap<>();
map_var.put("a", getResources().getString(R.string.perkadrenalinname));
map_var.put("b", getResources().getString(R.string.perksueberlebendenmegthomasname));
map_var.put("c", getResources().getString(R.string.perkslehrbarimblutnetzlevel40name));
map_var.put("d", getResources().getString(R.string.perkadrenalinpopupheadername));
map_var.put("e", getResources().getString(R.string.perkadrenalinpopuptxt));
map_list.add(map_var);
listview1.setAdapter(new Listview1Adapter(map_list));
((BaseAdapter)listview1.getAdapter()).notifyDataSetChanged();
saved = new Gson().toJson(map_list);
image_list.add(R.drawable.perk_ueberlebende);
image_list.add(R.drawable.adam_francis_perk_ablenkung);
image_list.add(R.drawable.meg_thomas_perk_adrenalin);
}
@Override
protected void onActivityResult(int _requestCode, int _resultCode, Intent _data) {
super.onActivityResult(_requestCode, _resultCode, _data);
switch (_requestCode) {
default:
break;
}
}
public class Listview1Adapter extends BaseAdapter {
ArrayList<HashMap<String, Object>> _data;
public Listview1Adapter(ArrayList<HashMap<String, Object>> _arr) {
_data = _arr;
}
@Override
public int getCount() {
return _data.size();
}
@Override
public HashMap<String, Object> getItem(int _index) {
return _data.get(_index);
}
@Override
public long getItemId(int _index) {
return _index;
}
@Override
public View getView(final int _position, View _view, ViewGroup _viewGroup) {
LayoutInflater _inflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View _v = _view;
if (_v == null) {
_v = _inflater.inflate(R.layout.perkssearch, null);
}
final LinearLayout linear1 = (LinearLayout) _v.findViewById(R.id.linear1);
final ImageView imageview1 = (ImageView) _v.findViewById(R.id.imageview1);
final LinearLayout linear2 = (LinearLayout) _v.findViewById(R.id.linear2);
final LinearLayout linear3 = (LinearLayout) _v.findViewById(R.id.linear3);
final TextView textview1 = (TextView) _v.findViewById(R.id.textview1);
final TextView textview2 = (TextView) _v.findViewById(R.id.textview2);
final TextView textview3 = (TextView) _v.findViewById(R.id.textview3);
textview1.setText(map_list.get((int)_position).get("a").toString());
textview2.setText(map_list.get((int)_position).get("b").toString());
textview3.setText(map_list.get((int)_position).get("c").toString());
imageview1.setImageResource(image_list.get((int)_position));
if (textview2.getText().equals(getResources().getString(R.string.perksueberlebende)) ) {
textview2.setTextColor(0xFFFFFFFF);
}
if (textview2.getText().equals(getResources().getString(R.string.perksvonkeinezuordnungname)) ) {
textview2.setTextColor(0xFFFFFFFF);
}
if (textview2.getText().equals(getResources().getString(R.string.perksueberlebendendwightfairfieldname)) ) {
textview2.setTextColor(0xFF8BC34A);
}
return _v;
}
}
@Deprecated
public void showMessage(String _s) {
Toast.makeText(getApplicationContext(), _s, Toast.LENGTH_SHORT).show();
}
@Deprecated
public int getLocationX(View _v) {
int _location[] = new int[2];
_v.getLocationInWindow(_location);
return _location[0];
}
@Deprecated
public int getLocationY(View _v) {
int _location[] = new int[2];
_v.getLocationInWindow(_location);
return _location[1];
}
@Deprecated
public int getRandom(int _min, int _max) {
Random random = new Random();
return random.nextInt(_max - _min + 1) + _min;
}
@Deprecated
public ArrayList<Double> getCheckedItemPositionsToArray(ListView _list) {
ArrayList<Double> _result = new ArrayList<Double>();
SparseBooleanArray _arr = _list.getCheckedItemPositions();
for (int _iIdx = 0; _iIdx < _arr.size(); _iIdx++) {
if (_arr.valueAt(_iIdx))
_result.add((double)_arr.keyAt(_iIdx));
}
return _result;
}
@Deprecated
public float getDip(int _input){
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, _input, getResources().getDisplayMetrics());
}
@Deprecated
public int getDisplayWidthPixels(){
return getResources().getDisplayMetrics().widthPixels;
}
@Deprecated
public int getDisplayHeightPixels(){
return getResources().getDisplayMetrics().heightPixels;
}
}

Related

Totally stumped...zoom control issue

I'm developing an application that utilizes zooming in and out (for readability) and allows for swiping left and right to change pages.
Basically the flipping back and forth part works and zoom works. However, if I do any kind of zooming and then try to change a page the program crashes.
I've only tested this on the Epic 4G and on the G2 with the same problem.
Any help that can tell me what is going on or what I need to change would be greatly appreciated. (I tried to code out on the net to fix the HTC incredible having this kind of issue but the problem is still there)
Code:
package my.package;
import java.io.IOException;
import java.io.InputStreamReader;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SubMenu;
import android.view.View;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.View.OnTouchListener;
import android.webkit.WebView;
public class LessonShower extends Activity {
private char[] buffer = new char[128];
private WebView webView;
private int lessonNumber, lessonPage;
private AssetManager assetManager;
private int lessonsCount;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int lessonNumber = getIntent().getIntExtra("lessonNumber", 1);
int lessonPage = getIntent().getIntExtra("lessonPage", 1);
webView = new MyWebView(this);
assetManager = getAssets();
try {
lessonsCount = assetManager.list("").length - 3;
loadPage(lessonNumber, lessonPage);
} catch (IOException e) {
}
SimpleOnGestureListener gestureListener = new SimpleOnGestureListener(){
private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
@Override
public boolean onDown(MotionEvent e) {
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2,
float velocityX, float velocityY) {
Log.d("debugging", "onFling");
if(Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY && e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE){
loadNextPage();
return true;
}
else if(e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE){
loadPrevPage();
return true;
}
if(e1.getY() - e2.getY() > SWIPE_MIN_DISTANCE){
webView.pageDown(false);
}
else if(e2.getY() - e1.getY() > SWIPE_MIN_DISTANCE){
webView.pageUp(false);
}
return super.onFling(e1, e2, velocityX, velocityY);
}
};
final GestureDetector gDetector = new GestureDetector(webView.getContext(), gestureListener);
webView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
return gDetector.onTouchEvent(arg1);
}
});
webView.getSettings().setBuiltInZoomControls(true);
setContentView(webView);
}
public void loadNextPage(){
int nextPage = lessonPage + 1;
try{
InputStreamReader is = new InputStreamReader(assetManager.open("lesson" + lessonNumber + "/" + nextPage + ".html"));
readPage(is);
lessonPage++;
}
catch(IOException ex){
final CharSequence[] items = {"Home", "Next lesson"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose an action");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if(item == 0){
finish();
}
else{
if(lessonNumber < lessonsCount){
lessonNumber++;
lessonPage = 1;
loadPage(lessonNumber, lessonPage);
}
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
public void loadPrevPage(){
if(lessonPage > 1){
try{
InputStreamReader is = new InputStreamReader(assetManager.open("lesson" + lessonNumber + "/" + --lessonPage + ".html"));
readPage(is);
}
catch(IOException ex){}
}
}
private void readPage(InputStreamReader is){
StringBuilder webPage = new StringBuilder();
int len = 0;
try {
while((len = is.read(buffer)) > 0){
webPage.append(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}
webView.loadData(webPage.toString(), "", "");
}
public void loadPage(int lessonNumber, int lessonPage){
if(lessonNumber > lessonsCount){
return;
}
this.lessonNumber = lessonNumber;
this.lessonPage = lessonPage;
setTitle("Lesson" + lessonNumber);
InputStreamReader is = null;
try {
is = new InputStreamReader(assetManager.open("lesson" + lessonNumber + "/" + lessonPage + ".html"));
} catch (IOException e) {
}
readPage(is);
}
private static final int homeMenuItem = 1;
private static final int exitMenuItem = 2;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(Menu.NONE, homeMenuItem, Menu.NONE, "Home");
SubMenu pagesMenu = menu.addSubMenu("Pages");
try {
int lessonPages = assetManager.list("lesson" + lessonNumber).length;
for(int i = 1; i <= lessonPages; i++)
//"+ 1000" is used to escape collision with other menu items
pagesMenu.add(Menu.NONE, i + 1000, Menu.NONE, "Page" + i);
} catch (IOException e) {}
finally{
menu.add(Menu.NONE, exitMenuItem, Menu.NONE, "Hide");
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch(item.getItemId()){
case homeMenuItem:
finish();
break;
case exitMenuItem:
moveTaskToBack(true);
break;
default:
//Page was selected
if(item.getItemId() > 1000){
lessonPage = item.getItemId() - 1000;
loadPage(lessonNumber, lessonPage);
}
}
return true;
}
}
class MyWebView extends WebView{
private LessonShower lp = null;
public MyWebView(Context context) {
super(context);
lp = (LessonShower) context;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event){
if(keyCode == KeyEvent.KEYCODE_DPAD_LEFT){
lp.loadPrevPage();
}
else if(keyCode == KeyEvent.KEYCODE_DPAD_RIGHT){
lp.loadNextPage();
}
return false;
}
}
No ideas? Anyone?
Sent from my SPH-D700 using XDA App

Help with ViewPager and Fragments

Hi all!
I've been developing an app that uses various things from my college and centralizes them in one app. I've made the app with two tabs - one for current students and one for prospective students. I would like to add the functionality of swiping between the two activities, and I saw that to do that, I want to convert my currentStudents and prospectiveStudents activities into fragments.
I have a couple of questions.
First, I don't quite understand how to accomplish converting the activities into fragments.
Second, I don't quite understand how to implement the viewPager effect.
If anyone can assist me in doing this, that'd be great. I've read through a lot of guides, but those guides are written to reflect other apps and it's pretty confusing.
Here is my MainActivity:
Code:
package com.andrew.obu;
import android.app.TabActivity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
public class MainActivity extends TabActivity {
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TabHost tabHost = getTabHost();
TabSpec cstudents = tabHost.newTabSpec("Current Students");
cstudents.setIndicator("Students");
Intent cstudentsIntent = new Intent(this, CurrentStudents.class);
cstudents.setContent(cstudentsIntent);
TabSpec prospects = tabHost.newTabSpec("Prospectives");
prospects.setIndicator("Prospectives");
Intent prospectsIntent = new Intent(this, ProspectiveStudents.class);
prospects.setContent(prospectsIntent);
tabHost.addTab(cstudents);
tabHost.addTab(prospects);
tabHost.getTabWidget().getChildAt(0).setBackgroundColor(Color.BLACK);
tabHost.getTabWidget().getChildAt(1).setBackgroundColor(Color.BLACK);
tabHost.setOnTabChangedListener(new OnTabChangeListener() {
@Override
public void onTabChanged(String arg0) {
TabHost tabHost = getTabHost();
setTabColor(tabHost);
}
});
setTabColor(tabHost);
}
public void setTabColor(TabHost tabhost) {
for(int i=0;i<tabhost.getTabWidget().getChildCount();i++)
tabhost.getTabWidget().getChildAt(i).setBackgroundColor(Color.BLACK); //unselected
if(tabhost.getCurrentTab()==0)
tabhost.getTabWidget().getChildAt(tabhost.getCurrentTab()).setBackgroundColor(Color.rgb(34, 34, 34)); //1st tab selected
else
tabhost.getTabWidget().getChildAt(tabhost.getCurrentTab()).setBackgroundColor(Color.rgb(34, 34, 34)); //2nd tab selected
}
}
And my code for the CurrentStudents Activity
Code:
package com.andrew.obu;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
public class CurrentStudents extends ListActivity {
private static final int MENU_ABOUT = 0;
private static final int MENU_CONTACT = 1;
int counter;
Button banner, email, moodle, jupiter, staff, calendar, athletics, news, prosp;
TextView display;
Drawable drawable;
@Override
public boolean onCreateOptionsMenu(android.view.Menu menu)
{
menu.add(0, MENU_ABOUT, 0, "About");
menu.add(0, MENU_CONTACT, 0, "Contact Me");
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
case MENU_ABOUT:
doSomething();
return true;
case MENU_CONTACT:
doSomethingElse();
return true;
}
return super.onOptionsItemSelected(item);
}
private void doSomethingElse() {
Intent intent = new Intent(getBaseContext(), Contact.class);
startActivity(intent);
}
private void doSomething() {
Intent intent = new Intent(getBaseContext(), About.class);
startActivity(intent);}
/*@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cstudents);*/
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] choose = getResources().getStringArray(R.array.cstudents_array);
ListView lv = getListView();
LayoutInflater lf;
View headerView;
lf = this.getLayoutInflater();
headerView = (View)lf.inflate(R.layout.cstudents, null, false);
lv.addHeaderView(headerView, null, false);
lv.setTextFilterEnabled(true);
lv.setBackgroundColor(Color.WHITE);
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_content, choose));
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Intent intent;
switch(position) {
default:
case 0 :
intent = new Intent(this, Bannerdisclaimer.class);
break;
case 2 :
intent = new Intent(this, Emailwebview.class);
break;
case 3 :
intent = new Intent(this, Moodlewebview.class);
break;
case 4 :
intent = new Intent(this, Jupiterwebview.class);
break;
case 5 :
intent = new Intent(this, Staffwebview.class);
break;
case 6 :
intent = new Intent(this, Calendar.class);
break;
case 7 :
intent = new Intent(this, Athleticswebview.class);
break;
case 8 :
intent = new Intent(this, Newswebview.class);
//intent7.putExtra("KEY_SELECTED_INDEX", position);
//startActivity(intent7);
break;
}
startActivity(intent);
};
}
//Resources res = getResources();
//drawable = res.getDrawable(R.drawable.bannera);
/*final Context context1 = this;
banner = (Button) findViewById(R.id.BannerButton);
banner.getBackground().setColorFilter(Color.rgb(148, 148, 148), PorterDuff.Mode.MULTIPLY);
banner.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myWebView = new Intent(context1, Bannerwebview.class);
startActivity(myWebView);
}
});
final Context context2 = this;
email = (Button) findViewById(R.id.EmailButton);
email.getBackground().setColorFilter(Color.rgb(148, 148, 148), PorterDuff.Mode.MULTIPLY);
email.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myWebView = new Intent(context2, Emailwebview.class);
startActivity(myWebView);
}
});
final Context context3 = this;
moodle = (Button) findViewById(R.id.MoodleButton);
moodle.getBackground().setColorFilter(Color.rgb(148, 148, 148), PorterDuff.Mode.MULTIPLY);
moodle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myWebView = new Intent(context3, Moodlewebview.class);
startActivity(myWebView);
}
});
final Context context4 = this;
jupiter = (Button) findViewById(R.id.JupiterButton);
jupiter.getBackground().setColorFilter(Color.rgb(148, 148, 148), PorterDuff.Mode.MULTIPLY);
jupiter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myWebView = new Intent(context4, Jupiterwebview.class);
startActivity(myWebView);
}
});
final Context context5 = this;
staff = (Button) findViewById(R.id.StaffButton);
staff.getBackground().setColorFilter(Color.rgb(148, 148, 148), PorterDuff.Mode.MULTIPLY);
staff.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myWebView = new Intent(context5, Staffwebview.class);
startActivity(myWebView);
}
});
final Context context = this;
calendar = (Button) findViewById(R.id.CalendarButton);
calendar.getBackground().setColorFilter(Color.rgb(148, 148, 148), PorterDuff.Mode.MULTIPLY);
calendar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context, Calendar.class);
startActivity(intent);
}
});
final Context context6 = this;
athletics = (Button) findViewById(R.id.AthleticsButton);
athletics.getBackground().setColorFilter(Color.rgb(148, 148, 148), PorterDuff.Mode.MULTIPLY);
athletics.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context6, Athleticswebview.class);
startActivity(intent);
}
});
final Context context7 = this;
news = (Button) findViewById(R.id.NewsButton);
news.getBackground().setColorFilter(Color.rgb(148, 148, 148), PorterDuff.Mode.MULTIPLY);
news.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context7, Newswebview.class);
startActivity(intent);
}
});*/
And my code for the ProspectiveStudents activity
Code:
package com.andrew.obu;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
public class ProspectiveStudents extends ListActivity
{
private static final int MENU_ABOUT = 0;
private static final int MENU_CONTACT = 1;
int counter;
Button banner, email, moodle, jupiter, staff, calendar, athletics, news, prosp;
TextView display;
Drawable drawable;
@Override
public boolean onCreateOptionsMenu(android.view.Menu menu)
{
menu.add(0, MENU_ABOUT, 0, "About");
menu.add(0, MENU_CONTACT, 0, "Contact Me");
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
case MENU_ABOUT:
doSomething();
return true;
case MENU_CONTACT:
doSomethingElse();
return true;
}
return super.onOptionsItemSelected(item);
}
private void doSomethingElse() {
Intent intent = new Intent(getBaseContext(), Contact.class);
startActivity(intent);
}
private void doSomething() {
Intent intent = new Intent(getBaseContext(), About.class);
startActivity(intent);}
/*@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cstudents);*/
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] choose = getResources().getStringArray(R.array.pstudents_array);
ListView lv = getListView();
LayoutInflater lf;
View headerView;
lf = this.getLayoutInflater();
headerView = (View)lf.inflate(R.layout.cstudents, null, false);
lv.addHeaderView(headerView, null, false);
lv.setTextFilterEnabled(true);
lv.setBackgroundColor(Color.WHITE);
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_content, choose));
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Intent intent;
switch(position) {
default:
case 0 :
intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.okbu.edu/admissions/onlineapp.html"));
break;
case 2 :
intent = new Intent(this, Majors.class);
break;
case 3 :
intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.okbu.edu/admissions/moreinfo.html"));
break;
case 4 :
intent = new Intent(this, Visitwebview.class);
break;
/*case 5 :
intent = new Intent(this, Getinvolved.class);
break;*/
}
startActivity(intent);
};
}
I recommend you to use ActionBarSherlock library: http://actionbarsherlock.com
Take a look at the samples and it will be easy to do what you ask for. At first, it may take a while to learn how to use this library, but you will not regret it since you will use it several times in the future for sure.
The coolest thing about this library is that it is compatible with older Android versions. I.e. The swipe effect will be available for Ice Cream users while for Froyo users will see two clickable tabs :good:
First of all, you can't swipe between activities. You can only swipe between fragments. Think of the activity as a container which holds your two fragments.
This is an example of a ListFragment:
Code:
public static class TitlesFragment extends ListFragment {
boolean mDualPane;
int mCurCheckPosition = 0;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Populate list with our static array of titles.
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_activated_1, Shakespeare.TITLES));
// Check to see if we have a frame in which to embed the details
// fragment directly in the containing UI.
View detailsFrame = getActivity().findViewById(R.id.details);
mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;
if (savedInstanceState != null) {
// Restore last state for checked position.
mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
}
if (mDualPane) {
// In dual-pane mode, the list view highlights the selected item.
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
// Make sure our UI is in the correct state.
showDetails(mCurCheckPosition);
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("curChoice", mCurCheckPosition);
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
showDetails(position);
}
/**
* Helper function to show the details of a selected item, either by
* displaying a fragment in-place in the current UI, or starting a
* whole new activity in which it is displayed.
*/
void showDetails(int index) {
mCurCheckPosition = index;
if (mDualPane) {
// We can display everything in-place with fragments, so update
// the list to highlight the selected item and show the data.
getListView().setItemChecked(index, true);
// Check what fragment is currently shown, replace if needed.
DetailsFragment details = (DetailsFragment)
getFragmentManager().findFragmentById(R.id.details);
if (details == null || details.getShownIndex() != index) {
// Make new fragment to show this selection.
details = DetailsFragment.newInstance(index);
// Execute a transaction, replacing any existing fragment
// with this one inside the frame.
FragmentTransaction ft = getFragmentManager().beginTransaction();
if (index == 0) {
ft.replace(R.id.details, details);
} else {
ft.replace(R.id.a_item, details);
}
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
} else {
// Otherwise we need to launch a new activity to display
// the dialog fragment with selected text.
Intent intent = new Intent();
intent.setClass(getActivity(), DetailsActivity.class);
intent.putExtra("index", index);
startActivity(intent);
}
}
}
I can't help you there because I've never worked with lists.
As for the swiping effect, build your project with a minimum SDK of 14 (ICS) and choose swipe-able tabs navigation. The ADT will do the job for you. Later, in order to maintain compatibility, use ABS library as patedit suggested.
Good luck
To implement a ViewPager, just add ViewPager to XML layout, and set a FragmentPageAdapter to it.
You must use support package from Android SDK and FragmentActivity instead of Activitiy.
You can examine source code of API Demos package to know more.

How to make the buttons in a fragment manipulate integer variables in seperate activi

This is a rudimentary android application that serves as an umpires strike/ball/out counter. There is a settings icon in the action bar of the MainActivity. When this icon is 'clicked on', a new Activity is started consisting of a PreferenceFragment, which consists of a checkboxpreference, and a Fragment that consists of 3 buttons. These buttons reset the stike_count, ball_count and total_outs_count to zero. I have spent a day on this and am having trouble figuring out how to manipulate integer variables in my MainActivity from button clicks in a seperate Activity's Fragment. Please point me in the right direction.
package edu.umkc.baldwin;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final String TAG = "UmpireActivity";
// Constant variables declared/initialized to keep track of values
// across lifecycle states
@SuppressWarnings("unused")
private static final String STRIKES = "0";
@SuppressWarnings("unused")
private static final String BALLS = "0";
@SuppressWarnings("unused")
private static final String OUTS = "0";
TextView strikeCounterTV;
TextView ballCounterTV;
TextView totalOutCounterTV;
private Button strikeCounterButton;
private Button ballCounterButton;
private int strike_count;
private int ball_count;
private int out_count;
private void updateViews(){
strikeCounterTV.setText(String.valueOf(strike_count));
ballCounterTV.setText(String.valueOf(ball_count));
totalOutCounterTV.setText(String.valueOf(out_count));
}
private void displayToast(boolean x){
int messageId = 0;
if (x == true){
messageId = R.string.strike_toast_view;
} else {
messageId = R.string.ball_toast_view;
}
Toast toast = Toast.makeText(MainActivity.this, messageId,
Toast.LENGTH_SHORT);
LinearLayout toastLayout = (LinearLayout) toast.getView();
TextView toastTV = (TextView) toastLayout.getChildAt(0);
toast.setGravity(Gravity.CENTER|Gravity.CENTER, 0, -150);
toastTV.setTextSize(42);
toast.show();
}
/*
* (non-Javadoc)
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "OnCreate(Bundle) called");
setContentView(R.layout.main_page_layout);
//Declare TextView objects and Button objects
strikeCounterTV = (TextView) findViewById(R.id.strikeCountTextView);
ballCounterTV = (TextView) findViewById(R.id.ballCountTextView);
totalOutCounterTV = (TextView) findViewById(R.id.totalOutsTextViewCounter);
strikeCounterButton = (Button) findViewById(R.id.strikeCountButton);
ballCounterButton = (Button) findViewById(R.id.ballCountButton);
strikeCounterButton.setOnClickListener(new OnClickListener(){
@override
public void onClick(View v) {
if (strike_count < 2){
strike_count++;
updateViews();
} else {
// batter has reached strike limit
displayToast(true);
out_count++;
strike_count = 0;
ball_count = 0;
updateViews();
}
}
});
ballCounterButton.setOnClickListener(new OnClickListener(){
@override
public void onClick(View v) {
if (ball_count < 3){
ball_count++;
updateViews();
} else {
// batter has reached ball limit
displayToast(false);
strike_count = 0;
ball_count = 0;
updateViews();
}
}
});
// Check for screen rotation
if (savedInstanceState == null){
strike_count = 0;
ball_count = 0;
} else {
strike_count = savedInstanceState.getInt("STRIKES");
ball_count = savedInstanceState.getInt("BALLS");
}
// Save 'totalOuts' variable through application exit
SharedPreferences savedObject = getPreferences(Context.MODE_PRIVATE);
out_count = savedObject.getInt(getString(R.string.total_outs_key), 0);
updateViews();
}
@override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
Log.d(TAG, "onSaveInstanceState() called");
savedInstanceState.putInt("STRIKES", strike_count);
savedInstanceState.putInt("BALLS", ball_count);
savedInstanceState.putInt("OUTS", out_count);
}
@override
public boolean onCreateOptionsMenu(Menu menu) {
//Displays actionbar items in app actionbar
getMenuInflater().inflate(R.menu.actionbar_layout, menu);
return super.onCreateOptionsMenu(menu);
}
@override
public boolean onOptionsItemSelected(MenuItem item){
super.onOptionsItemSelected(item);
switch (item.getItemId()){
case (R.id.reset_option):
strike_count = 0;
ball_count = 0;
updateViews();
return true;
case (R.id.about_menu_option):
Intent i = new Intent(this, About.class);
startActivity(i);
return true;
case (R.id.settings_menu_option):
Intent j = new Intent(this, SettingsActivity.class);
startActivity(j);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@override
public void onStart() {
super.onStart();
Log.d(TAG, "onStart() called");
}
@override
public void onPause() {
super.onPause();
Log.d(TAG, "onPause() called");
}
@override
public void onResume() {
super.onResume();
Log.d(TAG, "onResume() called");
}
@override
public void onStop() {
super.onStop();
Log.d(TAG, "onStop() called");
SharedPreferences out_file = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = out_file.edit();
editor.putInt(getString(R.string.total_outs_key), out_count);
editor.commit();
}
@override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy() called");
}
}
package edu.umkc.baldwin;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
public class SettingsActivity extends Activity {
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_layout);
FragmentManager ttsFragmentManager = getFragmentManager();
FragmentTransaction ttsFragmentTransaction = ttsFragmentManager.beginTransaction();
EnableTTSPreferenceFragment ttsFragment = new EnableTTSPreferenceFragment();
ttsFragmentTransaction.add(R.id.tts_fragment, ttsFragment);
ttsFragmentTransaction.commit();
FragmentManager resetFragmentManager = getFragmentManager();
FragmentTransaction resetFragmentTransaction = resetFragmentManager.beginTransaction();
ResetFragment resetFragment = new ResetFragment();
resetFragmentTransaction.add(R.id.reset_fragment, resetFragment);
resetFragmentTransaction.commit();
}
}
package edu.umkc.baldwin;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class ResetFragment extends Fragment {
@override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View resetFragment = inflater.inflate(R.layout.reset_layout, container, false);
return resetFragment;
}
}
package edu.umkc.baldwin;
import android.os.Bundle;
import android.preference.PreferenceFragment;
public class EnableTTSPreferenceFragment extends PreferenceFragment {
@override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.tts_preference_fragment);
}
@override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
}
To modify anything in your activity from one of its child Fragments you would typically create an interface in the Fragment and have the activity implement that. That interface would either contain one method setting all three vars or multiple ones, one for each variable. To call the methods in the interface call getActivity() and typecast it to the interface.

Face Detection in Background Service

I am making an android app which requires to capture image using front camera using android service. Also we need to detect face in the image so obtained. But when calling the detectfaces() function, the app unfortuantely stops. I am posting the code for it here. Please help me find out where i am going wrong.
here is my code..!!!!
package com.android.camerarecorder;
import android.app.Activity;
import android.content.Intent;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class CameraRecorder extends Activity implements SurfaceHolder.Callback {
static final int MAX_FACES = 5;
//private static final String TAG = "Recorder";
public static SurfaceView mSurfaceView;
public static SurfaceHolder mSurfaceHolder;
public static Camera mCamera;
public static boolean mPreviewRunning;
public static TextView jpgName;
public static ImageView jpgView;
public static ImageView imageView;
/** Called when the activity is first created. */
@SuppressWarnings("deprecation")
 @override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imageView = (ImageView)findViewById(R.id.jpgview);
mSurfaceView = (SurfaceView) findViewById(R.id.surfaceView1);
jpgName = (TextView)findViewById(R.id.jpgname);
jpgView = (ImageView)findViewById(R.id.jpgview);
mSurfaceHolder = mSurfaceView.getHolder();
mSurfaceHolder.addCallback(this);
mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
Button btnStart = (Button) findViewById(R.id.StartService);
btnStart.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(CameraRecorder.this,RecorderService.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startService(intent);
//finish();
}
});
Button btnStop = (Button) findViewById(R.id.StopService);
btnStop.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
stopService(new Intent(CameraRecorder.this, RecorderService.class));
}
});
}
@override
public void surfaceCreated(SurfaceHolder holder) {
}
@override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
}
The above code was the activity where the service is called. The service is as follows:
package com.android.camerarecorder;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.iutputStream;
import android.app.Service;
import android.content.ContentValues;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Parameters;
import android.media.AudioManager;
import android.media.FaceDetector;
import android.media.FaceDetector.Face;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class RecorderService extends Service
{
private SurfaceHolder sHolder;
private TextView mjpgname;
private ImageView mjpgview;
private ImageView mimageview;
Bitmap bm;
Bundle bundle = new Bundle();
String filename;
private int cameraId = 0;
//a variable to control the camera
private Camera mCamera;
final static String DEBUG_TAG = "Test";
Uri imageFileUri;
//the camera parameters
private Parameters parameters;
/** Called when the activity is first created. */
@override
public void onCreate()
{
super.onCreate();
sHolder=CameraRecorder.mSurfaceHolder;
mCamera = CameraRecorder.mCamera;
mjpgname= CameraRecorder.jpgName;
mjpgview = CameraRecorder.jpgView;
mimageview=CameraRecorder.imageView;
}
@SuppressWarnings("deprecation")
 @override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
// do we have a camera?
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Toast.makeText(this, "No camera on this device", Toast.LENGTH_LONG).show();
} else {
cameraId = findFrontFacingCamera();
if (cameraId < 0) {
Toast.makeText(this, "No front facing camera found.",Toast.LENGTH_LONG).show();
} else {
mCamera = Camera.open(cameraId);
}
}
//mCamera = Camera.open();
SurfaceView sv = new SurfaceView(getApplicationContext());
sv=CameraRecorder.mSurfaceView ;
try {
mCamera.setPreviewDisplay(sHolder);
parameters = mCamera.getParameters();
//set camera parameters
mCamera.setParameters(parameters);
mCamera.startPreview();
mCamera.takePicture(null, null, mCall);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Get a surface
sHolder = sv.getHolder();
//tells Android that this surface will have its data constantly replaced
sHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
private int findFrontFacingCamera() {
int cameraId = -1;
// Search for the front facing camera
int numberOfCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numberOfCameras; i++) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
Log.d(DEBUG_TAG, "Camera found");
cameraId = i;
break;
}
}
return cameraId;
// TODO Auto-generated method stub
}
Camera.PictureCallback mCall = new Camera.PictureCallback()
{
public void onPictureTaken(byte[] data, Camera camera)
{
//decode the data obtained by the camera into a Bitmap
// FileOutputStream outStream = null;
try{
imageFileUri = getContentResolver().insert(
Media.EXTERNAL_CONTENT_URI, new ContentValues());
OutputStream imageFileOS = getContentResolver().openOutputStream(
imageFileUri);
imageFileOS.write(data);
imageFileOS.flush();
imageFileOS.close();
filename = getRealPathFromURI(imageFileUri);
File imgFile = new File(filename);
if(imgFile.exists())
{
bm = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
mjpgview.setImageBitmap(bm);
}
detectFaces();
// mjpgname.setText("success");
/*
Intent i = new Intent(RecorderService.this, FaceDetect.class);
//Add your data to bundle
bundle.putString("Filepath", filename) ;
//Add the bundle to the intent
i.putExtras(bundle);
//Fire that second activity
startActivity(i);*/
/* final File images = Environment.getExternalStorageDirectory();
String filePath = "magic";
String final_path = images+"/"+filePath;
outStream = new FileOutputStream(final_path);
outStream.write(data);
outStream.close();*/
} catch (FileNotFoundException e){
Log.d("CAMERA", e.getMessage());
} catch (IOException e){
Log.d("CAMERA", e.getMessage());
}
}
};
private void detectFaces() {
if(null != bm){
int width = bm.getWidth();
int height = bm.getHeight();
FaceDetector detector = new FaceDetector(width, height,CameraRecorder.MAX_FACES);
Face[] faces = new Face[CameraRecorder.MAX_FACES];
Bitmap bitmap565 = Bitmap.createBitmap(width, height, Config.RGB_565);
Paint ditherPaint = new Paint();
Paint drawPaint = new Paint();
ditherPaint.setDither(true);
drawPaint.setColor(Color.RED);
drawPaint.setStyle(Paint.Style.STROKE);
drawPaint.setStrokeWidth(2);
Canvas canvas = new Canvas();
canvas.setBitmap(bitmap565);
//canvas.setBitmap(cameraBitmap);
canvas.drawBitmap(bm, 0, 0, ditherPaint);
int facesFound = detector.findFaces(bitmap565, faces);
// int facesFound = detector.findFaces(cameraBitmap, faces);
PointF midPoint = new PointF();
float eyeDistance = 0.0f;
float confidence = 0.0f;
Log.i("FaceDetector", "Number of faces found: " + facesFound);
if(facesFound > 0)
{
for(int index=0; index<facesFound; ++index){
faces[index].getMidPoint(midPoint);
eyeDistance = faces[index].eyesDistance();
confidence = faces[index].confidence();
Log.i("FaceDetector",
"Confidence: " + confidence +
", Eye distance: " + eyeDistance +
", Mid Point: (" + midPoint.x + ", " + midPoint.y + ")");
canvas.drawRect((int)midPoint.x - eyeDistance ,
(int)midPoint.y - eyeDistance ,
(int)midPoint.x + eyeDistance,
(int)midPoint.y + eyeDistance, drawPaint);
}
}
// Camera_timer.key = eyeDistance;
// tv.setText(eyeDistance+"");
String filepath = Environment.getExternalStorageDirectory()
+ "/facedetect" +System.currentTimeMillis() + ".jpg";
try {
FileOutputStream fos = new FileOutputStream(filepath);
bitmap565.compress(CompressFormat.JPEG, 90, fos);
// cameraBitmap.compress(CompressFormat.JPEG, 90, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mimageview.setImageBitmap(bitmap565);
// imageView.setImageBitmap(cameraBitmap);
}
}
private String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
//This method was deprecated in API level 11
//Cursor cursor = managedQuery(contentUri, proj, null, null, null);
CursorLoader cursorLoader = new CursorLoader((Context) mCall,contentUri, proj, null, null,null);
Cursor cursor = cursorLoader.loadInBackground();
int column_index =
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
// TODO Auto-generated method stub
}
@override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}

Load Image from RSS Enclosure tag???

Hello everyone.
I am trying to load the Images in an listview that the RSS provides me.
http://www.nutech.nl/rss is the rss i use.
i want to load the image in listview from these tags
<enclosure> </enclosure (
Code:
<enclosure url="http://media.nu.nl/m/m1nx89taa599_sqr256.jpg" length="None" type="image/jpeg"></enclosure>
)
Now i have tried several things i found on google but none worked or werent explaining enough.
Here is some of my main Codes
RSSreader.java
Code:
package com.thedutch.technews;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.os.StrictMode;
public class RSSReader {
DefaultHttpClient httpClient = new DefaultHttpClient();
public Document getRSSFromServer(String url) {
Document response = null;
response = getDomFromXMLString(getFeedFromServer(url));
return response;
}
private String getFeedFromServer(String url) {
String xml = null;
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
try {
HttpGet httpget =new HttpGet(url);
//HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpget);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (Exception e) {
e.printStackTrace();
}
return xml;
}
private Document getDomFromXMLString(String xml) {
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (Exception e) {
}
return doc;
}
public String getValue(Element item, String key) {
NodeList nodeList = item.getElementsByTagName(key);
return this.getElementValue(nodeList.item(0));
}
public final String getElementValue(Node node) {
Node child;
if (node != null) {
if (node.hasChildNodes()) {
for (child = node.getFirstChild(); child != null; child = child
.getNextSibling()) {
if (child.getNodeType() == Node.TEXT_NODE) {
return child.getNodeValue();
}
}
}
}
return "";
}
}
Nutech.java
Code:
package com.thedutch.technews;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import com.faizmalkani.floatingactionbutton.FloatingActionButton;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class Nutech extends Fragment implements OnClickListener{
String key_items = "item";
String key_title = "title";
String key_description = "description";
String key_link = "link";
String key_date = "pubDate";
ListView lstPost = null;
List<HashMap<String, Object>> post_lists = new ArrayList<HashMap<String, Object>>();
List<String> lists = new ArrayList<String>();
ArrayAdapter<String> adapter23 = null;
RSSReader rssfeed = new RSSReader();
FloatingActionButton mFab;
public static Fragment newInstance(Context context) {
Nutech f = new Nutech();
return f;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(
R.layout.activity_main4, container, false);
((MainActivity) getActivity())
.setActionBarTitle("Nutech");
mFab = (FloatingActionButton) view.findViewById(R.id.fabbutton);
mFab.setOnClickListener(this);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Appstatus.getInstance(getActivity()).isOnline()) {
lstPost = (ListView) getView().findViewById(R.id.lstPosts);
mFab = (FloatingActionButton) getView().findViewById(R.id.fabbutton);
mFab.listenTo(lstPost);
adapter23 = new ArrayAdapter<String>(getActivity(),
R.layout.feed_list_item, R.id.title, lists) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView txt1 = (TextView) view
.findViewById(R.id.title);
TextView txt2 = (TextView) view
.findViewById(R.id.desc);
TextView txt3 = (TextView) view
.findViewById(R.id.date);
HashMap<String, Object> data = post_lists.get(position);
txt1.setText(data.get(key_title).toString());
txt2.setText(data.get(key_description).toString());
txt3.setText(data.get(key_date).toString());
return view;
}
};
Document xmlFeed = rssfeed
.getRSSFromServer("http://www.nutech.nl/rss");
NodeList nodes = xmlFeed.getElementsByTagName("item");
for (int i = 0; i < nodes.getLength(); i++) {
Element item = (Element) nodes.item(i);
HashMap<String, Object> feed = new HashMap<String, Object>();
feed.put(key_title, rssfeed.getValue(item, key_title));
feed.put(key_description, rssfeed.getValue(item, key_description));
feed.put(key_link, rssfeed.getValue(item, key_link));
feed.put(key_date, rssfeed.getValue(item, key_date));
post_lists.add(feed);
lists.add(feed.get(key_title).toString());
}
lstPost.setAdapter(adapter23);
lstPost.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
if (Appstatus.getInstance(getActivity()).isOnline()) {
Document xmlFeed = rssfeed
.getRSSFromServer("http://www.nutech.nl/rss");
NodeList nodes = xmlFeed.getElementsByTagName("item");
Element item = (Element) nodes.item(position);
Intent indisplay = new Intent(getActivity(),PostViewActivity.class);
indisplay.putExtra("link", rssfeed.getValue(item, key_link));
startActivity(indisplay);
} else {
getActivity().setContentView(R.layout.activity_main3);
Thread background = new Thread() {
public void run() {
try {
sleep(5*1100);
getActivity().finish();
} catch (Exception e) {
}
}
};
background.start();
}
}
});
lstPost.setLongClickable(true);
lstPost.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long id) {
if (Appstatus.getInstance(getActivity()).isOnline()) {
Document xmlFeed = rssfeed
.getRSSFromServer("http://www.nutech.nl/rss");
NodeList nodes = xmlFeed.getElementsByTagName("item");
Element item = (Element) nodes.item(position);
final Intent wintent = new Intent(Intent.ACTION_VIEW).setData(Uri.parse(rssfeed.getValue(item, key_link)));
startActivity(wintent);
return true;
} else {
getActivity().setContentView(R.layout.activity_main3);
Thread background = new Thread() {
public void run() {
try {
sleep(5*1100);
getActivity().finish();
} catch (Exception e) {
}
}
};
background.start();
}
return true;
}
});
} else {
getActivity().setContentView(R.layout.activity_main3);
Thread background = new Thread() {
public void run() {
try {
sleep(5*1100);
getActivity().finish();
} catch (Exception e) {
}
}
};
background.start();
}
}
public void fabClicked(View view) {
adapter23.notifyDataSetChanged();
}
@Override
public void onClick(View v) {
adapter23.notifyDataSetChanged();
this.adapter23.notifyDataSetChanged();
lstPost.invalidateViews();
lstPost.refreshDrawableState();
Toast.makeText(this.getActivity(),
"Refreshed Nutech News!", Toast.LENGTH_LONG).show();
}
public void hideFab(View view) {
mFab.hide(true);
//getActionBar().hide();
}
public void showFab(View view) {
mFab.hide(false);
//getActionBar().show();
}
}
MainActivity.java
Code:
package com.thedutch.technews;
import java.util.ArrayList;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.analytics.tracking.android.MapBuilder;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
private EasyTracker easyTracker = null;
private Toolbar mToolbar;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private ListView mDrawerList;
private ArrayList<ListMenuModel> mListMenu;
private ListMenuAdapter mListMenuAdapter;
final String[] data ={"Nutech","Tweakers","Hardware Info"};
final String[] fragmentos ={
"com.thedutch.technews.Nutech",
"com.thedutch.technews.Tweakers",
"com.thedutch.technews.Hardwareinfo"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
easyTracker = EasyTracker.getInstance(MainActivity.this);
mToolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
setSupportActionBar(mToolbar);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mListMenu = new ArrayList<ListMenuModel>();
mListMenu.add(new ListMenuModel("Nutech", "Nutech", R.drawable.ic_nu));
mListMenu.add(new ListMenuModel("Tweakers", "Tweakers", R.drawable.ic_tweakers));
mListMenu.add(new ListMenuModel("Hardware Info", "Hardware Info", R.drawable.ic_hardwareinfo));
mListMenuAdapter = new ListMenuAdapter(getApplicationContext(),
mListMenu);
mDrawerList.setAdapter(mListMenuAdapter);
mDrawerList.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view, final int pos,long id){
mDrawerToggle.syncState();
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.content_frame, Fragment.instantiate(MainActivity.this, fragmentos[pos]));
tx.commit();
mDrawerList.setSelection(pos);
easyTracker.send(MapBuilder.createEvent("Nav Drawer",
"Opened Navigation Drawer", "Navigation Drawer", null).build());
mDrawerLayout.closeDrawer(mDrawerList);
}
});
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.content_frame,Fragment.instantiate(MainActivity.this, fragmentos[0]));
tx.commit();
mDrawerToggle = new ActionBarDrawerToggle(
this,
mDrawerLayout,
mToolbar,
R.string.drawer_open,
R.string.drawer_close){
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
syncState();
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
mToolbar.setClickable(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.about:
Intent intent = new Intent(this, AboutActivity.class);
this.startActivity(intent);
easyTracker.send(MapBuilder.createEvent("AboutActivity",
"Entered About Page", "about", null).build());
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
public void setActionBarTitle(String title) {
getSupportActionBar().setTitle(title);
}
@Override
public void onBackPressed() {
if(mDrawerLayout.isDrawerOpen(Gravity.START|Gravity.LEFT)){
mDrawerLayout.closeDrawers();
return;
}
super.onBackPressed();
}
public void fabClicked(View view) {
Toast.makeText(this, "Refreshed.", Toast.LENGTH_LONG).show();
}
@Override
public void onStart() {
super.onStart();
EasyTracker.getInstance(this).activityStart(this);
}
@Override
public void onStop() {
super.onStop();
EasyTracker.getInstance(this).activityStop(this);
}
}
is there someone who could help me ?
thank you
After few months i still havent found a solution or idea.
anyone here has ?
Use a RSS parsing library
Use my AndroidWithoutStupid Java library. It is on GitHub. There is also an article about the usage on CodeProject.
Enclosure tag is usually used for mp3 files but it doesn't matter.
After getting the enclosure value using the MvNewsFeed class, you need to download it. Use MvAsyncDownload for that. Then, use BitmapFactory.decodeFile() or a similar method to display the image in an ImageView.
SpaceCaker said:
After few months i still havent found a solution or idea.
anyone here has ?
Click to expand...
Click to collapse

Categories

Resources