Wasn't really sure how to ask this but...
My code is meant to generate ListView input on a button click.
When I click the button it should .execute() an Async which takes a list of items and adds them to an ArrayList< HashMap < String, String > > with a custom adapter.
The problem is, when I press the button, it generates the list and adds it to the ListView, however, instead of going... 1, 2, 3, 4, 5, ....20 it goes in a random order. 1, 2, 5, 1, 3, 0, 6, 7, 8, 3, 1 ...
And if I scroll up or down the ListView it changes.
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<Button
android:id="#+id/bLoadData"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Load api data" />
<ListView
android:id="#+id/lvMovies"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#id/bLoadData"
android:background="#efefef" />
</RelativeLayout>
results_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView android:id="#+id/ivPosters"
android:layout_width="120dp"
android:layout_height="120dp"
android:src="#drawable/place_holder_img"/>
<TextView
android:id="#+id/results_layout_tv_movie_name"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:paddingBottom="10dp"
android:paddingLeft="20dp"
android:paddingStart="20dp"
android:paddingTop="10dp"
android:text="hellow"
android:textColor="#000"
android:textSize="20sp" />
</LinearLayout>
</LinearLayout>
MainActivity.class:
package com.example.zdroa.testinggrounds;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
static ArrayList<HashMap<String, String>> posters;
ListView listView;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.lvMovies);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
System.out.println(posters.get(position).values().toString());
}
});
button = (Button) findViewById(R.id.bLoadData);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
posters = new ArrayList<>();
ImageLoadTask ilt = new ImageLoadTask();
ilt.execute();
}
});
}
private class ImageLoadTask extends AsyncTask<Void, Void, ArrayList<HashMap<String, String>>> {
#Override
protected ArrayList<HashMap<String, String>> doInBackground(Void... params) {
posters = getPathFromAPI();
return posters;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
SearchAdapter adapter = new SearchAdapter(MainActivity.this, result);
listView.setAdapter(adapter);
}
private ArrayList<HashMap<String, String>> getPathFromAPI() {
String moviePaths[] = new String[10];
for (int i = 0; i < moviePaths.length; i++) {
HashMap<String, String> map = new HashMap<>();
String s = "path";
map.put(s, s + "_" + i);
moviePaths[i] = "path_" + i;
posters.add(map);
}
return posters;
}
}
}
SearchAdapter.class:
package com.example.zdroa.testinggrounds;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.HashMap;
public class SearchAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<HashMap<String, String>> array;
private ImageView imageView;
private TextView textView;
SearchAdapter(Context context, ArrayList<HashMap<String, String>> paths) {
mContext = context;
array = paths;
}
#Override
public int getCount() {
return array.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = View.inflate(mContext, R.layout.results_layout, null);
imageView = (ImageView) convertView.findViewById(R.id.ivPosters);
textView = (TextView) convertView.findViewById(R.id.results_layout_tv_movie_name);
}
Drawable drawable = ContextCompat.getDrawable(mContext, R.drawable.place_holder_img);
String link_end = array.get(position).values().toString();
Picasso.with(mContext)
.load("http://image.tmdb.org/t/p/w185" + link_end)
// .resize(width, (int) (width * 1.5))
.placeholder(drawable)
.into(imageView);
textView.setText(position+"");
return convertView;
}
}
Your imageview and textview references are only set when the convertview is null...move those lines out of the parenthesis.
in onPost in Asyntask class
after creating and setting the adapter for listview
make the list that you're using in list view
list=new ArrayList<>();
Related
I'm trying to have a dialog where you can click a "next" button to swipe right to the next screen. I am doing that with a ViewPager and adapter:
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.voicedialog);
dialog.setCanceledOnTouchOutside(false);
MyPageAdapter adapter = new MyPageAdapter();
ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
pager.setAdapter(adapter);
However, I get a NullPointerException saying that pager is null. Why is this happening? Here is the Page Adapter class:
public class MyPageAdapter extends PagerAdapter {
public Object instantiateItem(ViewGroup collection, int position) {
int resId = 0;
switch (position) {
case 0:
resId = R.id.voice1;
break;
case 1:
resId = R.id.voice2;
break;
}
return collection.findViewById(resId);
}
#Override
public int getCount() {
return 2;
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
}
Here's my layout for the DIALOG:
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
Let me know on how to avoid this situation.
PS: Each of the layouts that should be in the view pager look like this, just diff. text:
<RelativeLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/voice2"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:text="Slide 1!"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView2"
android:layout_gravity="center"
android:textSize="50sp" />
</RelativeLayout>
Without Using Enum Class
You should call findViewById on dialog. so for that you have to add dialog before findViewById..
Like this,
ViewPager pager = (ViewPager) dialog.findViewById(R.id.viewpager);
After solving your null pointer exception the other problem's solution here, if you wont use enum class you can use below code...
MainActivity.java
package demo.com.pager;
import android.app.Dialog;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn= (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Dialog dialog = new Dialog(MainActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.voicedialog);
dialog.setCanceledOnTouchOutside(false);
MyPageAdapter adapter = new MyPageAdapter(MainActivity.this);
ViewPager pager = (ViewPager) dialog.findViewById(R.id.viewpager);
pager.setAdapter(adapter);
dialog.show();
}
});
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="demo.com.pager.MainActivity">
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</RelativeLayout>
MyPageAdapter.java
package demo.com.pager;
import android.app.FragmentManager;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by rucha on 26/12/16.
*/
public class MyPageAdapter extends PagerAdapter {
Context mContext;
int resId = 0;
public MyPageAdapter(Context context) {
mContext = context;
}
public Object instantiateItem(ViewGroup collection, int position) {
/* int resId = 0;
switch (position) {
case 0:
resId = R.id.voice1;
break;
case 1:
resId = R.id.voice2;
break;
}
return collection.findViewById(resId);*/
LayoutInflater inflater = LayoutInflater.from(mContext);
switch (position) {
case 0:
resId = R.layout.fragment_blue;
break;
case 1:
resId = R.layout.fragment_pink;
break;
}
ViewGroup layout = (ViewGroup) inflater.inflate(resId, collection, false);
collection.addView(layout);
return layout;
}
#Override
public int getCount() {
return 2;
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
}
FragmentBlue.java
package demo.com.pager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import android.support.v4.app.Fragment;
public class FragmentBlue extends Fragment {
private static final String TAG = FragmentBlue.class.getSimpleName();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_blue, container, false);
return view;
}
}
fragment_blue.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#4ECDC4">
</RelativeLayout>
voicedialog.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Please check and reply.
Using Enum Class
Try this code, This is working if any doubt ask again. Happy to help.
MainActivity.java
package demo.com.dialogdemo;
import android.app.Dialog; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.Window; import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupUIComponents();
setupListeners();
}
private void setupUIComponents() {
button = (Button) findViewById(R.id.button);
}
private void setupListeners() {
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialogItemDetails = new Dialog(MainActivity.this);
dialogItemDetails.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialogItemDetails.setContentView(R.layout.dialoglayout);
dialogItemDetails.getWindow().setBackgroundDrawable(
new ColorDrawable(Color.TRANSPARENT));
ViewPager viewPager = (ViewPager) dialogItemDetails.findViewById(R.id.viewPagerItemImages);
viewPager.setAdapter(new CustomPagerAdapter(MainActivity.this));
dialogItemDetails.show();
}
});
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="dialog" />
</RelativeLayout>
ModelObject1.java
public enum ModelObject1 {
RED(R.string.red, R.layout.fragment_one),
BLUE(R.string.blue, R.layout.fragment_two);
private int mTitleResId;
private int mLayoutResId;
ModelObject1(int titleResId, int layoutResId) {
mTitleResId = titleResId;
mLayoutResId = layoutResId;
}
public int getTitleResId() {
return mTitleResId;
}
public int getLayoutResId() {
return mLayoutResId;
}
}
CustomPagerAdapter.java
package demo.com.dialogdemo;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by rucha on 26/12/16.
*/
public class CustomPagerAdapter extends PagerAdapter {
private Context mContext;
public CustomPagerAdapter(Context context) {
mContext = context;
}
#Override
public Object instantiateItem(ViewGroup collection, int position) {
ModelObject1 modelObject = ModelObject1.values()[position];
LayoutInflater inflater = LayoutInflater.from(mContext);
ViewGroup layout = (ViewGroup) inflater.inflate(modelObject.getLayoutResId(), collection, false);
collection.addView(layout);
return layout;
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
collection.removeView((View) view);
}
#Override
public int getCount() {
return ModelObject1.values().length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public CharSequence getPageTitle(int position) {
ModelObject1 customPagerEnum = ModelObject1.values()[position];
return mContext.getString(customPagerEnum.getTitleResId());
}
}
dailoglayout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/txtHeaderTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center"
android:text="ITEM IMAGES"
android:textStyle="bold" />
<android.support.v4.view.ViewPager
android:id="#+id/viewPagerItemImages"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white" />
</RelativeLayout>
fragmentone.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="one"/>
</LinearLayout>
I am new in android
The structure of my application consist of:
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.example.reyhane.myapplication.MainActivity">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.design.widget.CoordinatorLayout>
cell.xml
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layoutDirection="rtl">
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/nationalCode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="2"
android:layout_marginLeft="8dp"
android:textStyle="bold" />
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="2"
android:layout_marginLeft="8dp"
android:textStyle="bold" />
<TextView
android:id="#+id/lastName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="2"
android:layout_marginLeft="8dp"
android:textStyle="bold" />
<Button
android:id="#+id/delete_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="2"
android:text="حذف" />
</TableRow>
</TableLayout>
MainActivity.java
package com.example.reyhane.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity extends Activity {
public ListView list;
public ArrayList<Person> countries = new ArrayList<Person>();
public ListAdapter adapter;
public void fillPerson(String nationalCode) {
Person person = new Person();
person.setNationalCode(nationalCode);
person.setName("reza");
person.setLastName("hghgh");
person.setPhone("231345");
countries.add(person);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
fillPerson("6768767");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.list);
adapter = new ListAdapter(this);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
Object o = list.getItemAtPosition(position);
Person person = (Person) o;
openAddPersonActivity(person.getNationalCode());
}
});
}
public void openAddPersonActivity(String nationalCode) {
Intent i = new Intent(MainActivity.this, AddPerson.class);
if (nationalCode != null)
i.putExtra("nationalCode", nationalCode);
startActivity(i);
}
}
ListAdapter.java
package com.example.reyhane.myapplication;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TableLayout;
import android.widget.TextView;
/**
* Created by reyhane on 11/24/16.
*/
public class ListAdapter extends BaseAdapter {
MainActivity mainActivity;
ListAdapter(MainActivity mainActivity) {
this.mainActivity = mainActivity;
}
#Override
public int getCount() {
return mainActivity.countries.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
static class ViewHolderItem {
TextView nationalCode;
TextView name;
TextView lastName;
TextView phone;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolderItem holder = new ViewHolderItem();
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mainActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.cell, null);
holder.nationalCode = (TextView) convertView.findViewById(R.id.nationalCode);
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.lastName = (TextView) convertView.findViewById(R.id.lastName);
convertView.setTag(holder);
} else {
holder = (ViewHolderItem) convertView.getTag();
}
Button deleteBtn = (Button) convertView.findViewById(R.id.delete_btn);
holder.nationalCode.setText(this.mainActivity.countries.get(position).getNationalCode());
holder.name.setText(this.mainActivity.countries.get(position).getName());
holder.lastName.setText(this.mainActivity.countries.get(position).getLastName());
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something
mainActivity.countries.remove(position); //or some other task
notifyDataSetChanged();
}
});
return convertView;
}
}
My problem:
As you see in my application, i have list of person in listview.
In this form i add person and delete and edit it.
I can remove each record of listview but i can not get nationalCode value of person of each reacord in listview to fetch person from database by this nationalcode and edit it.
How do i do?
please help me
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3)
{
String nationalcode = (String) ((TextView) v.findViewById(R.id.nationalcode)).getText();
Toast.makeText(getApplicationContext(), "NATIONAL CODE "+nationalcode, Toast.LENGTH_SHORT).show();
openAddPersonActivity(nationalcode);
}
});
Hope it helps.
try this :
openAddPersonActivity(countries.get(position).getNationalCode());
FYI, the list.setOnItemClick doesn't work
add this into your ListAdapter:
holder.nationalCode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(mainActivity,"Country Code = "+MainActivity.countries.get(position).getNationalCode(),Toast.LENGTH_SHORT).show();
Intent i = new Intent(mainActivity, AddPerson.class);
if (nationalCode != null)
i.putExtra("nationalCode", nationalCode);
startActivity(i);
}
});
and if you click country code in listview item then it will detected;
You have not set countries list to your Listview adaptor.
When you are setting the adaptor, pass the countries list to listview adaptor.
It work successfully:
holder.nationalCode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String nationalcode = (String) ((TextView) view.findViewById(R.id.nationalCode)).getText();
Toast.makeText(mainActivity, "NATIONAL CODE " + nationalcode, Toast.LENGTH_SHORT).show();
}
});
Try This
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
Person person = countries.get(position);
openAddPersonActivity(person.getNationalCode());
}
**I have this code to show the installed applications in Android. I also want to display the selected applications by the user in Grid view. How can I do that in this code?
And is there always a need for adapter for grid-view also?**
This is my first activity:
package com.abhi.test;
import java.util.ArrayList;
import com.example.applist.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Startup extends Activity {
Button bIns, bSel;
ArrayList<String> myList = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bIns = (Button) findViewById(R.id.bList);
bSel = (Button) findViewById(R.id.bGrid);
}
public void viewList(View view) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
public void viewGrid(View view) {
myList = (ArrayList<String>) getIntent().getSerializableExtra("mySelectedList");
Intent intent = new Intent(getApplicationContext(), Last.class);
intent.putExtra("mySelectedList",myList);
startActivity(intent);
}
}
This is my second activity:
package com.abhi.test;
import java.util.ArrayList;
import com.abhi.test.ApplicationAdapter;
import java.util.List;
import com.example.applist.R;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
private PackageManager packageManager = null;
private List<ApplicationInfo> applist = null;
private ApplicationAdapter listadaptor = null;
Button button;
Bundle bundle;
CheckBox checkbox;
ArrayList<ApplicationInfo> selectedapplication = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
packageManager = getPackageManager();
button = (Button) findViewById(R.id.button);
checkbox = (CheckBox) findViewById(R.id.cb_app);
new LoadApplications().execute();
//Intent intent = new Intent(this,Last.class);
}
public void selectedApps(View view) {
//new ApplicationAdapter().selApps();
selectedapplication = ApplicationAdapter.finalList;
Intent intent = new Intent(MainActivity.this, Startup.class);
intent.putExtra("mySelectedList",selectedapplication);
startActivity(intent);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
ApplicationInfo app = applist.get(position);
try {
Intent intent = packageManager
.getLaunchIntentForPackage(app.packageName);
if (null != intent) {
startActivity(intent);
}
} catch (ActivityNotFoundException e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG)
.show();
} catch (Exception e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG)
.show();
}
}
private List<ApplicationInfo> checkForLaunchIntent(
List<ApplicationInfo> list) {
ArrayList<ApplicationInfo> applist = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info : list) {
try {
if (packageManager.getLaunchIntentForPackage(info.packageName) != null)
{
applist.add(info);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return applist;
}
private class LoadApplications extends AsyncTask<Void, Void, Void> {
private ProgressDialog progress = null;
#Override
protected Void doInBackground(Void... params) {
applist = checkForLaunchIntent(packageManager
.getInstalledApplications(PackageManager.GET_META_DATA));
listadaptor = new ApplicationAdapter(MainActivity.this,
R.layout.row, applist);
return null;
}
#Override
protected void onPostExecute(Void result) {
setListAdapter(listadaptor);
progress.dismiss();
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
progress = ProgressDialog.show(MainActivity.this, null,
"Loading application info...");
super.onPreExecute();
}
}
}
Array adapter for second activity:
package com.abhi.test;
import java.util.ArrayList;
import java.util.List;
import com.example.applist.R;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class ApplicationAdapter extends ArrayAdapter<ApplicationInfo> {
private List<ApplicationInfo> appsList = null;
private Context context;
int position1;
CheckBox checkBox;
private PackageManager packageManager;
public ArrayList<Boolean> checkList = new ArrayList<Boolean>();
private OnCheckedChangeListener listener;
public static ArrayList<ApplicationInfo> finalList = null;
public ApplicationAdapter(Context context, int textViewResourceId,
List<ApplicationInfo> appsList) {
super(context, textViewResourceId, appsList);
this.context = context;
this.appsList = appsList;
packageManager = context.getPackageManager();
for (int i = 0; i < appsList.size(); i++)
{
checkList.add(false);
}
}
#Override
public int getCount() {
if (appsList != null) {
return appsList.size();
} else {
return 0;
}
}
#Override
public ApplicationInfo getItem(int position) {
if (appsList != null) {
return appsList.get(position);
} else {
return null;
}
}
#Override
public long getItemId(int position) {
return position;
}
#Override //ibuilt function getView()--responsinle for making views
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if ( view == null) {
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE); //Understand
view = layoutInflater.inflate(R.layout.row, null);
}
ApplicationInfo data = appsList.get(position);
if (data != null) {
TextView appName = (TextView) view.findViewById(R.id.app_name);
TextView packageName = (TextView) view.findViewById(R.id.app_paackage);
ImageView iconview = (ImageView) view.findViewById(R.id.app_icon);
position1=position;
checkBox = (CheckBox) view.findViewById(R.id.cb_app); //understand
checkBox.setTag(Integer.valueOf(position)); // set the tag so we can identify the correct row in the listener
checkBox.setChecked(checkList.get(position)); // set the status as we stored it
checkBox.setOnCheckedChangeListener(mListener); // set the listener
appName.setText(data.loadLabel(packageManager));
packageName.setText(data.packageName);
iconview.setImageDrawable(data.loadIcon(packageManager));
/* if(checkBox.isChecked())
{
finalList.add(data);
Toast.makeText(getContext(), "App Added", Toast.LENGTH_LONG).show();
}*/
}
return view;
}
OnCheckedChangeListener mListener = new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
checkList.set((Integer)buttonView.getTag(),isChecked); // get the tag so we know the row and store the status
}
};
}
This is the last activity in which I want to show the selected applications by the user:
package com.abhi.test;
import java.util.ArrayList;
import com.example.applist.R;
import android.app.Activity;
import android.content.pm.ApplicationInfo;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.GridView;
public class Last extends Activity{
GridView gridview;
ArrayList<ApplicationInfo> appList;
String[] appName = new String[100];
String[] appPack = new String[100];
String[] appComp = new String[100];
ArrayList<String> appInfo = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.last);
gridview = (GridView) findViewById(R.id.gridview);
appList = (ArrayList<ApplicationInfo>) getIntent().getSerializableExtra("mylist");
for(int i=0;i<appList.size();i++)
{
appName[i] = appList.get(i).name;
appPack[i] = appList.get(i).packageName;
appComp[i] = appName[i]+appPack[i];
appInfo.add(appComp[i]);
}
/* ArrayAdapter<ApplicationInfo> adapter = new ArrayAdapter<ApplicationInfo>(this,
android.R.layout.simple_list_item_1, appInfo);
gridview.setAdapter(adapter);*/
}
}
XML for the first activity:
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rootLayout"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
android:orientation="vertical" >
<Button
android:id="#+id/bList"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="fill_horizontal"
android:onClick="viewList"
android:text="#string/bInstalledApps" />
<Button
android:id="#+id/bGrid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="fill_horizontal"
android:onClick="viewGrid"
android:text="#string/bSelectedApps" />
</LinearLayout>
XML for the second activity:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:onClick="selectedApps"
android:text="Done"/>
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/button" />
</RelativeLayout>
row.xml for adapter:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/appdata"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<CheckBox
android:id="#+id/cb_app"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:gravity="center_vertical"
android:scaleX="1.50"
android:scaleY="1.50" />
<ImageView
android:id="#+id/app_icon"
android:layout_width="50dp"
android:layout_height="50dp"
android:padding="3dp"
android:scaleType="centerCrop" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:orientation="vertical"
android:paddingLeft="5dp" >
<TextView
android:id="#+id/app_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:textStyle="bold" />
<TextView
android:id="#+id/app_paackage"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical" />
</LinearLayout>
</LinearLayout>
XML for the last activity:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rootLayout"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
android:orientation="vertical" >
<GridView
android:id="#+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="90dp"
android:gravity="center"
android:horizontalSpacing="10dp"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="10dp" />
</LinearLayout>
A GridView is a collection of views in a grid. The Android system doesn't magically know what views you want to be in it. This is where the adapter comes in. By setting an adapter for a GridView, you tell the GridView several things about how you want it to display views including how many views there are and what each view looks like. So yes, all GridViews need adapters.
I am new to android programming and I seem to have come at a stand still for several days now. I am having trouble finding a solution to my problem and tried many different solutions without success. As the title suggests, my code runs successfully but the ListView does not show up on the selected Tabs. Any suggestions of tips would be helpful.
ItemGuide.Java ------------------------------------
package com.example.alzuni_project;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
public class ItemGuide extends SherlockFragmentActivity {
private ViewPager mViewPager;
private TabsAdapter mTabsAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mViewPager = new ViewPager(this);
mViewPager.setId(R.id.pager);
setContentView(mViewPager);
final ActionBar bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
bar.setDisplayShowTitleEnabled(false);
bar.setDisplayShowHomeEnabled(false);
mTabsAdapter = new TabsAdapter(this, mViewPager);
mTabsAdapter.addTab(bar.newTab().setIcon(R.drawable.leathertab_image), LeatherTab.class, null);
mTabsAdapter.addTab(bar.newTab().setIcon(R.drawable.leathertab_image), SilverTab.class, null);
}
}
LeatherTab.java --------------------------------------------------------------
package com.example.alzuni_project;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockFragment;
public class LeatherTab extends SherlockFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.leather_fragment, container, false); //Fragment Layout inflated
TextView text = (TextView) view.findViewById(R.id.boxtest);//TextView for layout testing
text.setText("Hello");
ListView leather_listview = (ListView) view.findViewById(R.id.leather_list); // List is initialized
leather_listview.setAdapter(new LeatherAdapter(getActivity())); //Custom list adapter passes Context
return view;
}
}
LeatherAdapter.java ------------------------------------------------------
package com.example.alzuni_project;
import java.util.ArrayList;
import android.content.Context;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
class LeatherAdapter extends BaseAdapter {
ArrayList<SingleRow> list;
Context context;
public LeatherAdapter(Context c) {
context = c;
list = new ArrayList<SingleRow>();
Resources res = c.getResources();
String[] titles = res.getStringArray(R.array.leather_list_titles);
String[] descriptions = res.getStringArray(R.array.leather_list_description);
int[] images = {R.drawable.belt, R.drawable.wallet, R.drawable.coincase};
for (int i=0;i<images.length;i++) //Was originally 3
{
new SingleRow(titles[i], descriptions[i], images[i]);
}
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.single_row, viewGroup, false);
TextView title = (TextView) row.findViewById(R.id.leather_title);
TextView description = (TextView) row.findViewById(R.id.leather_description);
ImageView image = (ImageView) row.findViewById(R.id.leather_icon);
SingleRow temp = list.get(position);
title.setText(temp.title);
description.setText(temp.description);
image.setImageResource(temp.image);
return row;//returns the rootView of single_row.xml
}
}
leatherfragment.xml ------------------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/boxtest"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#CCDDFF" />
<ListView
android:id="#+id/leather_list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/boxtest" />
</RelativeLayout>
SingleRow.java -----------------------------------------------------
package com.example.alzuni_project;
class SingleRow {
String title;
String description;
int image;
SingleRow(String title, String description, int image) {
this.title=title;
this.description=description;
this.image=image;
}
}
single_row.xml ---------------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/leather_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="48dp"
android:layout_marginTop="48dp"
android:contentDescription="#string/todo" />
<TextView
android:id="#+id/leather_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/leather_icon"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#CCCCCC" />
<TextView
android:id="#+id/leather_description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/leather_icon"
android:layout_alignLeft="#+id/leather_icon"
android:layout_alignParentRight="true"
android:layout_below="#+id/leather_title"
android:background="#CCDDFF" />
Your list seems empty , try this in your LeatherAdapter:
list.add(new SingleRow(titles[i],descriptions[i], images[i]));
Inside the for loop .
I am newbie in android. I want to create a custom listview arrayadapter. I have followed some tutorial but my emulator shows nothing for the Custom ListView. Can anyone help me figure out where is wrong with my code? Thanks in advance.
Here is my custom_listview_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/customListView" />
</LinearLayout>
This is my custom_listview_row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:minHeight="64dp">
<!-- <ImageView
android:id="#+id/clv_imageView"
android:layout_width="32dp"
android:layout_height="32dp"
android:contentDescription="#string/empty"
android:layout_alignParentLeft="true"
android:layout_marginLeft="9dp"
android:layout_alignParentTop="true"/> -->
<TextView
android:id="#+id/clv_textView2"
android:layout_width="97dp"
android:layout_height="32dp"
android:layout_alignParentRight="true"
android:gravity="center_vertical"
android:text="#string/tv_definition"
android:textIsSelectable="true" />
<TextView
android:id="#+id/clv_textView"
android:layout_width="97dp"
android:layout_height="32dp"
android:layout_alignParentLeft="true"
android:gravity="center_vertical"
android:text="#string/tv_word"
android:textIsSelectable="true" />
</RelativeLayout>
Here is my MyPerformanceArrayAdapter.java
import java.util.List;
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.TextView;
public class MyPerformanceArrayAdapter extends ArrayAdapter<DefinitionObject>{
private List<DefinitionObject> entries;
private Activity activity;
public MyPerformanceArrayAdapter(Activity a, int textViewResourceId, List<DefinitionObject> entries) {
super(a, textViewResourceId, entries);
this.entries = entries;
this.activity = a;
}
public static class ViewHolder{
public TextView item1;
public TextView item2;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder;
if (v == null) {
LayoutInflater vi =
(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.custom_listview_row, null);
holder = new ViewHolder();
holder.item1 = (TextView) v.findViewById(R.id.clv_textView);
holder.item2 = (TextView) v.findViewById(R.id.clv_textView2);
v.setTag(holder);
}
else
holder=(ViewHolder)v.getTag();
final DefinitionObject custom = entries.get(position);
if (custom != null) {
holder.item1.setText(custom.getWord());
holder.item2.setText(custom.getFav());
}
return v;
}
}
and lastly, this is my Activity named TempCLV.java
package com.example.myidictionary;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ListView;
public class TempCLV extends Activity {
private MySQLiteDefinitionHelper db;
String tblName = "";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom_listview_main);
Intent msjIntent = getIntent();
tblName = msjIntent.getStringExtra(WordDefinitionHomeActivity.TABLENAME2);
}
public void refresh()
{
db = new MySQLiteDefinitionHelper(this);
final List<DefinitionObject> values = db.getAllWords(tblName);
ListView mylist = (ListView)findViewById(R.id.customListView);
MyPerformanceArrayAdapter adapter = new MyPerformanceArrayAdapter(this, R.id.customListView, values);
mylist.setAdapter(adapter);
}
}
You need to call refresh in onCreate since you are setting the adapter to list view there.
Make sure your values has some data
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom_listview_main);
Intent msjIntent = getIntent();
tblName = msjIntent.getStringExtra(WordDefinitionHomeActivity.TABLENAME2);
refresh();
}
Also you can move the inflater initialization to the constructor of adapter class. No need to initialize in getView
LayoutInflater vi;
public MyPerformanceArrayAdapter(Activity a, int textViewResourceId,List<DefinitionObject> entries) {
super(a, textViewResourceId, entries);
this.entries = entries;
vi =(LayoutInflater)a.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
Please call refresh method at least for first time to set the the adapter in your MainActivity' onCreate method..