how to display the next images by clicking on the "next" button - android

I am trying to display the image by clicking on the "next" button but this code doesn't work.
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
public class MyGridView extends Activity {
GridView mGridView;
int counter,i;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.mygridacti);
mGridView = (GridView)findViewById(R.id.grdvw);
//mGridView.setAdapter(new MyImageAdapter(this));
ImageView imageview = (ImageView)findViewById(R.id.GalleryView);
Button btnnext = (Button)findViewById(R.id.btn_nxt);
Log.i("counter", ""+counter);
btnnext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//for(i=0;i<=5;i++){
mGridView.setAdapter(new MyImageAdapter(getApplicationContext()));
Log.i("counter", ""+counter);
//}
// TODO Auto-generated method stub
//mGridView.setAdapter(new MyImageAdapter(getApplicationContext()));
//Toast.makeText(MyGridView.this, "No Images", Toast.LENGTH_SHORT).show();
}
}
);
}
}
class MyImageAdapter extends BaseAdapter{
private Context mContext;
ImageView imageview;
int counter;
public MyImageAdapter(Context c){
mContext = c;
}
public MyImageAdapter(OnClickListener onClickListener) {
// TODO Auto-generated constructor stub
}
#Override
public int getCount() {
// TODO Auto-for(i = 6;i<=counter;i++) {generated method stub
//counter = mThumbsIds.length;
//System.out.println("Counter = "+counter);
return 5;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if(convertView == null){
imageview = new ImageView(mContext);
imageview.setLayoutParams(new GridView.LayoutParams(85,85));
imageview.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageview.setPadding(8, 8, 8, 8);
}
else{
imageview = (ImageView) convertView;
}
//int[] mThumbIds = null;
imageview.setImageResource(mThumbsIds[position]);
return imageview;
//return null;
}
private Integer[] mThumbsIds = {
R.drawable.image1,R.drawable.image2,
R.drawable.image3,R.drawable.image4,
R.drawable.image5,R.drawable.icon,
R.drawable.icon,R.drawable.icon,
R.drawable.icon};
}
Please help me out to correct this.

To refresh grid view see this search result

Related

Accessing an element-Button in grid view

I am supposed to access a button of an element in a grid view and supposed to capture the onItemClick() activity of that button, but somehow I am not able to do it. Help me out. I am posting my code below. Please check it.
package com.nik.cardone;
import java.util.ArrayList;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
public class Fragment2 extends Fragment{
GridView fragment2Grid;
POJOMenuGrid pojo;
ArrayList<POJOMenuGrid> arr;
String[] name = {"Manchow Soup","Clear Soup","Mushroom Soup","Corn Soup","Tomato Soup"};
String[] desc = {"Soya water with capsicum , carrots , medium spicy"};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View v = inflater.inflate(R.layout.new_order_fragment_2, null);
initialize();
fragment2Grid = (GridView)v.findViewById(R.id.fragment2Grid);
fragment2Grid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
View v = arg0.getChildAt(arg2);
// TODO Auto-generated method stub
System.out.println("In grid :");
}
});
for(int i=0;i<5;i++){
arr.add(new POJOMenuGrid(name[i], desc[0], R.drawable.t2));
}
System.out.println(arr.get(0).getName()+" "+arr.get(0).getDescription()+" ");
CustomGridAdapter adapter = new CustomGridAdapter(v.getContext(), arr);
fragment2Grid.setAdapter(adapter);
System.out.println("adapter set");
return v;
}
private void initialize() {
// TODO Auto-generated method stub
arr = new ArrayList<POJOMenuGrid>();
}
}
Custom Adapter
package com.nik.cardone;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomGridAdapter extends BaseAdapter{
Context context;
ArrayList<POJOMenuGrid> arr;
LayoutInflater inflater;
TextView itemName;
TextView itemDescription;
ImageView itemImage;
Button plus;
Button minus;
TextView counter;
public CustomGridAdapter(Context context, ArrayList<POJOMenuGrid> arr) {
super();
this.context = context;
this.arr = arr;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
System.out.println("in constructor");
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return arr.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arr.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
System.out.println("in adapter 1");
arg1 = inflater.inflate(R.layout.grid_single_item, null);
System.out.println("in adapter 2");
itemName = (TextView)arg1.findViewById(R.id.itemName);
itemDescription = (TextView)arg1.findViewById(R.id.itemDescription);
//counter = (TextView)arg1.findViewById(R.id.counter);
itemImage = (ImageView)arg1.findViewById(R.id.itemImage);
plus = (Button)arg1.findViewById(R.id.plus);
minus = (Button)arg1.findViewById(R.id.minus);
plus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
System.out.println("In plus :");
// TODO Auto-generated method stub
TextView counter = (TextView)arg0.findViewById(R.id.counter);
int counter1 = Integer.parseInt(counter.getText().toString());
counter1++;
counter.setText(""+counter1);
}
});
minus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
TextView counter = (TextView)arg0.findViewById(R.id.counter);
int counter1 = Integer.parseInt(counter.getText().toString());
counter1--;
counter.setText(""+counter1);
}
});
System.out.println("in adapter 3");
itemName.setText(arr.get(arg0).getName());
itemDescription.setText(arr.get(arg0).getDescription());
itemImage.setImageResource(arr.get(arg0).getImage());
System.out.println("in adapter 4");
return arg1;
}
}

How to sort adapter (BaseAdapter) based on current its field

I have listviewadapter , it contains some fields like : status, notes, salesname, insertdate (txtTgglInsert), image. I want to do sorting based insertdate(txtTgglInsert) descending(based on recent status). How could I do this one on my programm with calling this adapter?
my adapter :
import java.net.URL;
import java.text.DecimalFormat;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class ListViewTimelineAdapter extends BaseAdapter{
private static ArrayList<URLPostClass> DataProcessorResult;
private LayoutInflater myInflater;
Context mycontext;
public ListViewTimelineAdapter(Context context, ArrayList<URLPostClass> results) {
DataProcessorResult = results;
myInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
//Log.d("count", String.valueOf(DataProcessorResult.size()));
return DataProcessorResult.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return DataProcessorResult.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
final ViewHolder holder;
final Context mycontext=parent.getContext();
if(convertView == null) {
convertView = myInflater.inflate(R.layout.custom_viewtimeline, null);
holder = new ViewHolder();
holder.txtJenisStatus = (TextView) convertView.findViewById(R.id.jenisstatus);
holder.txtStatus = (TextView) convertView.findViewById(R.id.status);
holder.txtSales = (TextView) convertView.findViewById(R.id.sales);
holder.txtTgglInsert = (TextView) convertView.findViewById(R.id.tgglinsert);
holder.imgPosting= (ImageView) convertView.findViewById(R.id.imgposting);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.txtJenisStatus.setText(DataProcessorResult.get(position).getJenisStatus());
holder.txtStatus.setText(DataProcessorResult.get(position).getRemark());
holder.txtSales.setText(DataProcessorResult.get(position).getNamaSales());
holder.txtTgglInsert.setText(DataProcessorResult.get(position).getTgglInsert());
holder.txtStatus.setTextSize(TypedValue.COMPLEX_UNIT_PX, mycontext.getResources().getDimensionPixelSize( R.dimen.lbltitlelistviewitem));
holder.txtJenisStatus.setTextSize(TypedValue.COMPLEX_UNIT_PX, mycontext.getResources().getDimensionPixelSize( R.dimen.lbllistviewitem));
holder.txtSales.setTextSize(TypedValue.COMPLEX_UNIT_PX, mycontext.getResources().getDimensionPixelSize( R.dimen.lbllistviewitem));
holder.txtTgglInsert.setTextSize(TypedValue.COMPLEX_UNIT_PX, mycontext.getResources().getDimensionPixelSize( R.dimen.lbllistviewitem));
try {
String image_url = DataProcessorResult.get(position).getPath();
if (image_url.length()>0) {
ImageLoader imgLoader = new ImageLoader(mycontext);
imgLoader.DisplayImage(image_url, 0, holder.imgPosting);
holder.imgPosting.getLayoutParams().width= mycontext.getResources().getDimensionPixelSize( R.dimen.photolistviewitem);
holder.imgPosting.getLayoutParams().height= mycontext.getResources().getDimensionPixelSize( R.dimen.photolistviewitem);
}else {
holder.imgPosting.setVisibility(View.GONE);
}
} catch (Exception e) {
// TODO Auto-generated catch block
//Toast.makeText(mycontext, e.toString(), Toast.LENGTH_SHORT).show();
}
//if (position % 2 == 1) {convertView.setBackgroundColor(Color.WHITE);} else {convertView.setBackgroundColor(Color.rgb(208,212,208)); }
return convertView;
}
static class ViewHolder {
TextView txtJenisStatus;
TextView txtStatus;
TextView txtSales;
TextView txtTgglInsert;
ImageView imgPosting;
}
}
Since your Adapter is based on an ArrayList of objects, you can change your implementation to subclass ArrayAdapter (Docs: http://developer.android.com/reference/android/widget/ArrayAdapter.html)
public class ListViewTimelineAdapter extends ArrayAdapter<URLPostClass> {
after that, sorting would be trivial:
ArrayList<URLPostClass> myListData = ...
ArrayAdapter<URLPostClass> adapter = new MyArrayAdapter<URLPostClass>(context, R.layout.my_layout, myListData);
adapter.sort(new Comparator<URLPostClass>() {
#Override public int compare(URLPostClass lhs, URLPostClass rhs) {
return rhs.getTgglInsert().compareTo(lhs.getTgglInsert()); // flipped for reverse order
}
});
myListView.setAdapter(adapter);
Considering that you've got a Date field your Comaparator class would be like this
public class CustomDateComparator implements Comparator<DataProcessorResult> {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat ("dd MMM yyyy");
#Override
public int compare(DataProcessorResult lhs, DataProcessorResult rhs) {
// TODO Auto-generated method stub
Date lhsDate = null;
Date rhsDate = null;
try {
lhsDate = simpleDateFormat.parse(lhs.getTgglInsert());
rhsDate = simpleDateFormat.parse(rhs.getTgglInsert());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(lhsDate == rhsDate) {
return lhs.getNamaSales().compareToIgnoreCase(rhs.getNamaSales());
}else {
return lhsDate.compareTo(rhsDate);
}
}
}
And then you can do this
Collections.sort(results, new CustomDateComparator());
just before you pass it to your custom adapter class.
Hope this helps you.

trying to add a Custom ListView With an Adapter to a Fragment?

I'm trying to add a Custom ListView With an Adapter to a Fragment.
I don't Know where is the problem exactly, I think I got everything in place yet I cant get rid of the Unfortunately Stopped message.
I Used the debug and knew where it all collapses ;
in the Fragment class at the
for (int i = 0;i<4;i++){
.
.
.
questions.add(question);
when the debug reaches this statement it ends.
Fragment
import java.util.List;
import code.me.R.id;
import android.R.layout;
import android.app.Application.ActivityLifecycleCallbacks;
import android.app.Fragment;
import android.annotation.SuppressLint;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
#SuppressLint("NewApi")
public class Fragment1 extends Fragment
{
ListView lv;
List<Question> questions;
Integer[] Q_Id ;
String[] AskerUserName = {"Jack" ,"John" ,"Lio" ,"Sam" ,"Mike" };
String[] AnswererUserName ={"Jacob" ,"Mario" ,"Tom" ,"Shon" ,"Jasmine" };
String[] Qusetion = {"What?" ,"Where?" ,"When" ,"How?" ,"Who?" };
String[] Answer = {"jjjjjjjjjj","llllllll","fffffffff","eeeeeeeeeeee","oooooooooooo"};
#Override
public View onCreateView( LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState )
{
for (int i = 0;i<4;i++){
int qid = i;
String AUName = AskerUserName[i].toString();
String AnUName = AnswererUserName[i].toString();
String Ans = Answer[i].toString();
String Ques = Qusetion[i].toString();
Question question = new Question(qid, AUName, AnUName, Ans, Ques);
questions.add(question);
}
View view = inflater.inflate(R.layout.frag1, container, false);
QuestionsAdapter questad = new QuestionsAdapter(getActivity(),questions);
lv = (ListView) view.findViewById(id.listView1);
lv.setAdapter(questad);
return inflater.inflate( R.layout.frag1,
container, false );
}
}
Adapter
import java.util.List;
import code.me.R.id;
import android.R.layout;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class QuestionsAdapter extends BaseAdapter {
private final Activity context;
public List<Question> questions;
LayoutInflater inflater;
public QuestionsAdapter(Activity context,List<Question> qu) {
this.context = context;
this.questions = qu;
// TODO Auto-generated constructor stub
}
#Override
public View getView(int position, View view , ViewGroup parent){
View rowView = view;
if(view == null)
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.question_answer_item, null,false);
TextView askerUserName = (TextView) view.findViewById(id.askerUsername);
askerUserName.setText(questions.get(position).getAskerUserName().toString());
TextView question = (TextView) view.findViewById(id.Question);
question.setText(questions.get(position).getQuestion().toString());
TextView ratingView = (TextView) view.findViewById(id.RatingAsker);
//ratingView.setText(questions.get(position)._RatingU);
TextView ratingAnswerer = (TextView) view.findViewById(id.RatingAnswerer);
//ratingAnswerer.setText(questions.get(position).getRatingView());
return rowView;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 0;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return questions.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return questions.get(position)._QId;
}
}
Class_Question
public class Question {
private
String _Answer ;
String _AnswererUserName;
String _AskerUserName ;
String _Question ;
Integer _QId;
Integer _RatingU;
Integer _RatingQ;
public Question (int Q_Id,String AUName,String AnUName,String Ans,String Ques){
_QId = Q_Id;
_AnswererUserName = AnUName;
_AskerUserName = AUName;
_Answer = Ans;
_Question = Ques;
}
public String getAnswer() {
// TODO Auto-generated method stub
return _Answer;
}
public String getAnswererUserName() {
// TODO Auto-generated method stub
return _AnswererUserName;
}
public String getAskerUserName() {
// TODO Auto-generated method stub
return _AskerUserName;
}
public String getQuestion() {
// TODO Auto-generated method stub
return _Question;
}
public int getRatingView() {
// TODO Auto-generated method stub
return _RatingU;
}
public void setRatingQ() {
// TODO Auto-generated method stub
}
public int getRatingQ() {
// TODO Auto-generated method stub
return _RatingQ;
}
}
You never initialize the List<Question> questions in your fragment.
You never initialize your question collection. That's why it stops when you try to add questions in onCreateView. Either initialize List questions initially or some time before you try to add things to it.

How to solve a ResourcesNotFoundException in Android

This is my code , I have a problem ,error message about ResourcesNotFoundException this is a piece of code to view employees it has 2 buttons one to do delete and the other to do update.
I don't know the reason of this exception.
package com.example.task_9;
import java.util.ArrayList;
import com.example.task_9.my_dataBase.employees_con;
import com.example.task_9.my_dataBase.my_database;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class manage extends Activity {
ListView listview;
TextView totalrecords,tv;
//my_database db;
public ArrayList<employees> emp_list ;
employees_con con;
//Button logout;
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
setContentView(R.layout.manage);
tv = (TextView) findViewById(R.id.textView1);
tv.setText("Employees Record:");
totalrecords = (TextView) findViewById(R.id.textView2);
listview = (ListView) findViewById(R.id.listView1);
// logout=(Button) findViewById(R.id.button1);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
emp_list = new ArrayList<employees>();
emp_list.clear();
con = new employees_con(this);
// db = new my_database(getApplicationContext());
// db.getWritableDatabase();
ArrayList<employees> e_list =con.getAllData() ;
for (int i = 0; i < e_list.size(); i++) {
Log.d("for_getall ", "ok ");
int e_id = e_list.get(i).getId();
Log.d("fun_getall ", "ok ");
// System.out.println("tidno>>>>>" + tidno);
String e_name = e_list.get(i).getUser_name();
String e_password = e_list.get(i).getPassword();
int e_age = e_list.get(i).getAge();
int e_status = e_list.get(i).getStatus();
Log.d("fun_getall ", "ok ");
employees emp_model = new employees();
emp_model.setId(e_id);
emp_model.setUser_name(e_name);
emp_model.setPassword(e_password);
emp_model.setAge(e_age);
emp_model.setStatus(e_status);
Log.d("addlist ", "ok ");
emp_list.add(emp_model);
}
Log.d("out for ", "ok ");
totalrecords.setText("Total Records :-" + emp_list.size());
listview.setAdapter(new ListAdapter(this));
con.close();
}
private class ListAdapter extends BaseAdapter {
//ArrayList<employees> data=new ArrayList<employees>();
Context contxt;
TextView id;
TextView user_name;
TextView password;
TextView age;
TextView status;
ImageView img;
employees obj;
LayoutInflater inflater;
public ListAdapter(Context context) {
// TODO Auto-generated constructor stub
contxt=context;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return emp_list.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View v, ViewGroup parent) {
// TODO Auto-generated method stub
/*if (v == null) {
v = inflater.inflate(R.layout.view, null);}*/
if (v == null)
{
LayoutInflater vi = (LayoutInflater)contxt.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.view, null); // album_list.xml this layout of the custom listview
Log.d("view if", "ok ");
}
id=(TextView) v.findViewById(R.id.textView6);
user_name=(TextView) v.findViewById(R.id.textView7);
password=(TextView) v.findViewById(R.id.textView8);
age=(TextView) v.findViewById(R.id.textView9);
status=(TextView) v.findViewById(R.id.textView10);
img =(ImageView) v.findViewById(R.id.imageView1);
Log.d("out if", "ok ");
obj = emp_list.get(position);
user_name.setText(obj.getUser_name());
id.setText(obj.getId());
password.setText(obj.getPassword());
age.setText(obj.getAge());
status.setText(obj.getStatus());
Log.d("view else ", "ok ");
final int temp = position;
(v.findViewById(R.id.button1))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
int emp_id=emp_list.get(temp).getId();
String emp_name = emp_list.get(temp).getUser_name();
String emp_password = emp_list.get(temp).getPassword();
int emp_age=emp_list.get(temp).getAge();
int emp_status=emp_list.get(temp).getStatus();
Intent intent = new Intent(manage.this,update.class);
Bundle bundle = new Bundle();
bundle.putInt("id", emp_id);
bundle.putString("name", emp_name);
bundle.putString("password", emp_password);
bundle.putInt("age", emp_age);
bundle.putInt("status", emp_status);
intent.putExtras(bundle);
startActivity(intent);
}
});
(v.findViewById(R.id.button2))
.setOnClickListener(new OnClickListener() {
employees_con con=new employees_con(contxt);
public void onClick(View arg0) {
AlertDialog.Builder alertbox = new AlertDialog.Builder(manage.this);
alertbox.setCancelable(true);
alertbox.setMessage("Are you sure you want to delete ?");
alertbox.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface arg0, int arg1) {
con.DeleteEmp(emp_list.get(temp).getUser_name().toString());
con.close();
manage.this.onResume();
Toast.makeText(
getApplicationContext(),
"Record Deleted...",
Toast.LENGTH_SHORT).show();
}
});
alertbox.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface arg0, int arg1) {
Toast.makeText(
getApplicationContext(),
"No Clicked...",
Toast.LENGTH_SHORT).show();
}
});
alertbox.show();
}
});
return v;
}
}
}
}
Change
id.setText(obj.getId());
with
id.setText(String.valueOf(obj.getId()));
if you pass an int as argument for a TextView android will look for a String with id the int you provide. If it does not found throws an exception
One important this is that you should use Activity.onCreate() method in place of Activity.onStart().

Android Application lister

I have created an app that I want to list all the installed applications to to a custom listview. bt unfortunately the activity crashes at the start! can any one please help me on this! I cant find the error, since it does not give any!
AppActivity.java
package com.ex.layout;
import java.util.List;
import android.app.Activity;
import android.content.pm.PackageInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
public class AppActivity extends Activity implements OnItemClickListener{
String[] name = getaAppName();
String[] packs = getPackName();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView li = (ListView) findViewById(R.id.applist);
ListviewAdapet list = new ListviewAdapet(this, name, packs);
li.setAdapter(list);
li.setOnItemClickListener(this);
}
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(this,"Title => "+name[position]+"=> n Description"+packs[position], Toast.LENGTH_SHORT).show();
}
public String[] getaAppName() {
List<PackageInfo> apps = getPackageManager().getInstalledPackages(0);
String appname[] = new String[apps.size()];
for (int number = 0; number < apps.size(); number++) {
PackageInfo pack = apps.get(number);
appname[number] = pack.applicationInfo.loadLabel(getPackageManager()).toString();
}
return appname;
}
public String[] getPackName(){
List<PackageInfo> apps = getPackageManager().getInstalledPackages(0);
String packnames[] = new String[apps.size()];
for (int i = 0; i < apps.size(); i++) {
PackageInfo pack = apps.get(i);
packnames[i] = pack.packageName;
}
return packnames;
}
}
this is the next class! it extends baseadapter to get the output.
listviewadapet.java
package com.ex.layout;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class ListviewAdapet extends BaseAdapter{
Activity context;
String[] appname , packname;
public ListviewAdapet(Activity Context, String[] appname , String[] packname) {
// TODO Auto-generated constructor stub
super();
this.appname = appname;
this.packname = packname;
this.context = Context;
}
public class Viewholder{
TextView appname;
TextView packname;
}
public int getCount(String[] array) {
// TODO Auto-generated method stub
int count = array.length;
return count;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Viewholder view;
LayoutInflater inflator = context.getLayoutInflater();
if (convertView == null) {
convertView = inflator.inflate(R.layout.listitem, null);
view = new Viewholder();
view.appname = (TextView) convertView.findViewById(R.id.appname);
view.packname= (TextView) convertView.findViewById(R.id.packagename);
convertView.setTag(view);
} else {
view = (Viewholder) convertView.getTag();
}
view.appname.setText(appname[position]);
view.packname.setText(packname[position]);
return convertView;
}
public int getCount() {
// TODO Auto-generated method stub
return 0;
}
}
Please help me on this!
Thank you.
You have done two serious errors in code.
Error 1
String[] name = getaAppName();
String[] packs = getPackName();
You are calling these two methods before onCreate.REMEMBER getPackageManager needs Activity context.If you define it before onCreate you will get damn NullPointerException
So change your code
from
public class AppActivity extends Activity implements OnItemClickListener{
String[] name = getaAppName();
String[] packs = getPackName();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
To
public class AppActivity extends Activity implements OnItemClickListener{
String[] name;
String[] packs;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
name = getaAppName();
packs = getPackName();
Error 2
public int getCount() {
// TODO Auto-generated method stub
return 0;
}
You will get Empty list if you return 0 here.
So change it to
public int getCount() {
return packname.length;
}

Categories

Resources