Android ListView with ArrayAdapter doesn't show anything - java

I know there are a lot of posts on how to make an Android ListView, but even after looking through most of them I can't figure out what my problem is. I'm completely new to Android and obviously a bit overwhelmed. The activity runs but without showing any content.
This is my Activity:
package com.example.myfirstapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
public class HistoryActivity extends Activity {
CustomRowAdapter customRowAdapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
listView = (ListView)findViewById(R.id.listView);
customRowAdapter = new CustomRowAdapter(getApplicationContext());
listView.setAdapter(customRowAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.history, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
this is activity_history.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:orientation="vertical">
<ListView
android:id="#+id/listView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
The xml for the input in the ListView (custom_row.xml):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:orientation="vertical">
<TextView
android:id="#+id/textView1"
android:background="#drawable/box"
android:textSize="18sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/app_name" />
<TextView
android:id="#+id/textView2"
android:background="#drawable/box"
android:textSize="18sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/app_name" />
<TextView
android:id="#+id/textView3"
android:background="#drawable/box"
android:textSize="18sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/app_name" />
</LinearLayout>
and CustomRowAdapter.java:
package com.example.myfirstapp;
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 CustomRowAdapter extends ArrayAdapter<String> {
private String[] text1 = {
"Google Plus",
"Twitter",
"Facebook",
"Instagram"};
private String[] text2 = {
"test1",
"test2",
"test3",
"test4"};
private String[] text3 = {
"Google Plus",
"Twitter",
"Facebook",
"Instagram"};
private LayoutInflater layoutInflater;
private Context context;
public CustomRowAdapter(Context context) {
super(context,0);
layoutInflater= (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.context=context;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup){
view = layoutInflater.inflate(R.layout.custom_row,null);
TextView textViewT1 = (TextView)view.findViewById(R.id.textView1);
TextView textViewT2 = (TextView)view.findViewById(R.id.textView2);
TextView textViewT3 = (TextView)view.findViewById(R.id.textView3);
// textViewT1.setText("test");
// textViewT2.setText(text2[0]);
// textViewT3.setText(text3[0]);
return view;
}
#Override
public int getCount(){
return 0;
}
}
Hope somebody can help me out.

Your ListView is not showing nothing because of
#Override
public int getCount(){
return 0;
}
getCount has to return the number of elements that belong to your dataset. For instance
#Override
public int getCount(){
return text1.length;
}

You're returning 0 from getCount. Return the number of items in the list here, I suspect you want something like text1.length.

Hey i see my simple and best example, Follow some steps
I mostly use custom for testing
JSON Parsing
Step 1.
JSONParser.java
public class JSONParser {
InputStream is = null;
JSONObject jObj = null;
String json = "";
// constructor
public JSONParser() {
}
public String getJSONFromUrl(String url) {
// Making HTTP request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
Log.e("response", "" + httpResponse);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
json = sb.toString();
is.close();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
return json;
}
}
Sept 2.
MainHome.java
public class MainActivity extends Activity {
ListView lvdata;
LinkedList<HashMap<String, String>> aldata = new LinkedList<HashMap<String, String>>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
new getData().execute();
}
void init() {
lvdata = (ListView) findViewById(R.id.lvdata);
}
private class getData extends AsyncTask<Void, Void, String> {
Dialog dialog;
String url;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
url = "Enter your url";
JSONParser jParser = new JSONParser();
String json = jParser.getJSONFromUrl(url);
try {
JSONObject jobject = new JSONObject(json);
int success = jobject.getInt("success");
for (int i = 0; i < jobject.length() - 1; i++) {
JSONObject jobj = jobject
.getJSONObject(Integer.toString(i));
if (success == 1) {
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("p_name", jobj.getString("p_name"));
hm.put("p_title", jobj.getString("p_title"));
aldata.add(hm);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (dialog != null)
if (dialog.isShowing())
dialog.dismiss();
Custom_Adapter adapter = new Custom_Adapter(
(Activity) MainActivity.this, aldata);
lvdata.setAdapter(adapter);
}
}
}
Custom Adapter
Custom_Adapter.java
public class Custom_Adapter extends ArrayAdapter<HashMap<String, String>> {
private final Activity context;
private final LinkedList<HashMap<String, String>> allData;
public Custom_Adapter(Activity context,
LinkedList<HashMap<String, String>> list) {
super(context, R.layout.custom_list, list);
this.context = context;
this.allData = list;
}
static class ViewHolder {
TextView tvname, tvinfo;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
view = null;
if (view == null) {
LayoutInflater inflator = context.getLayoutInflater();
view = inflator.inflate(R.layout.custom_list, null);
final ViewHolder viewHolder = new ViewHolder();
initAll(view, viewHolder);
view.setTag(viewHolder);
}
ViewHolder holder = (ViewHolder) view.getTag();
fillAll(holder, position);
return view;
}
public void initAll(View view, ViewHolder viewHolder) {
viewHolder.tvname = (TextView) view.findViewById(R.id.tvname);
viewHolder.tvinfo = (TextView) view.findViewById(R.id.tvinfo);
}
public void fillAll(final ViewHolder holder, final int position) {
holder.tvname.setText(allData.get(position).get("p_name"));
holder.tvinfo.setText(allData.get(position).get("p_title"));
}
}

Related

No virtual method getLayoutInflater [duplicate]

This question already has answers here:
getLayoutInflater() in fragment
(5 answers)
Closed 4 years ago.
I'm trying to code an app that downloads data of some events from an online MySQL database and writes it into my android app. Right now, what i'm trying to do is just testing if downloading the name of the event works, but i keep getting this error:
java.lang.NoSuchMethodError: No virtual method getLayoutInflater()Landroid/view/LayoutInflater; in class Lcom/suspicio/appfisio_business/FrammentoCorsi; or its super classes (declaration of 'com.suspicio.appfisio_business.FrammentoCorsi' appears in /data/app/com.suspicio.appfisio_business-1/split_lib_slice_8_apk.apk)
at com.suspicio.appfisio_business.FrammentoCorsi$EventoAdapter.getView(FrammentoCorsi.java:204)
which points to the line:
listViewItem = getLayoutInflater().inflate(R.layout.frammento_corsi, null, true);
Here's my code (it's a fragment):
FrammentoCorsi.java:
public class FrammentoCorsi extends Fragment {
public static final int CODE_GET_REQUEST = 1024;
public static final int CODE_POST_REQUEST = 1025;
public FrammentoCorsi() { //Vuoto
}
boolean isUpdating = false;
View rootView;
List<Evento> eventoList;
ListView listView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.frammento_corsi, container, false);
listView = (ListView) rootView.findViewById(R.id.listViewEventi);
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
eventoList = new ArrayList<>();
readEventi();
}
private void readEventi() {
PerformNetworkRequest request = new PerformNetworkRequest(Api.URL_READ_EVENTI, null, CODE_GET_REQUEST);
request.execute();
}
private void refreshEventoList(JSONArray eventi) throws JSONException {
//clearing previous heroes
eventoList.clear();
//traversing through all the items in the json array
//the json we got from the response
for (int i = 0; i < eventi.length(); i++) {
//getting each hero object
JSONObject obj = eventi.getJSONObject(i);
//adding the hero to the list
eventoList.add(new Evento(
obj.getInt("id"),
obj.getString("titolo"),
obj.getString("inizio"),
obj.getString("fine"),
obj.getInt("categoria"),
obj.getString("link"),
obj.getString("luogo")
));
}
//creating the adapter and setting it to the listview
EventoAdapter adapter = new EventoAdapter(eventoList);
listView.setAdapter(adapter);
}
//inner class to perform network request extending an AsyncTask
public class PerformNetworkRequest extends AsyncTask<Void, Void, String> {
//the url where we need to send the request
String url;
//the parameters
HashMap<String, String> params;
//the request code to define whether it is a GET or POST
int requestCode;
ProgressBar barra = (ProgressBar) getView().findViewById(R.id.progressBar);
//constructor to initialize values
PerformNetworkRequest(String url, HashMap<String, String> params, int requestCode) {
this.url = url;
this.params = params;
this.requestCode = requestCode;
}
//when the task started displaying a progressbar
#Override
protected void onPreExecute() {
super.onPreExecute();
barra.setVisibility(View.VISIBLE);
}
//this method will give the response from the request
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
barra.setVisibility(View.INVISIBLE);
try {
JSONObject object = new JSONObject(s);
if (!object.getBoolean("error")) {
Toast.makeText(getActivity().getApplicationContext(), object.getString("message"), Toast.LENGTH_SHORT).show();
refreshEventoList(object.getJSONArray("eventi"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
//the network operation will be performed in background
#Override
protected String doInBackground(Void... voids) {
RequestHandler requestHandler = new RequestHandler();
if (requestCode == CODE_POST_REQUEST)
return requestHandler.sendPostRequest(url, params);
if (requestCode == CODE_GET_REQUEST)
return requestHandler.sendGetRequest(url);
return null;
}
}
class EventoAdapter extends ArrayAdapter<Evento> {
List<Evento> eventoList;
//constructor to get the list
public EventoAdapter(List<Evento> eventoList) {
super(getActivity(), R.layout.frammento_corsi, eventoList);
this.eventoList = eventoList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listViewItem = convertView;
if (listViewItem == null) {
listViewItem = getLayoutInflater().inflate(R.layout.frammento_corsi, null, true);
}
//getting the textview for displaying name
TextView textViewName = listViewItem.findViewById(R.id.nomeeventocalendario);
//the update and delete textview
//ImageView textViewUpdate = listViewItem.findViewById(R.id.notifica);
//ImageView textViewDelete = listViewItem.findViewById(R.id.link);
final Evento evento = eventoList.get(position);
textViewName.setText(evento.getTitolo());
return listViewItem;
}
}
}
And its resource file frammento_corsi.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.suspicio.appfisio_business.FrammentoCorsi">
<ListView
android:id="#+id/listViewEventi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/nomeeventocalendario"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:visibility="gone"/>
</FrameLayout>
Can you help me out?
Thanks in advance!
Use this
LayoutInflater layoutInflater = LayoutInflater.from(getContext());
listViewItem = layoutInflater.inflate(R.layout.frammento_corsi, null ,true);
Instead of this
listViewItem = getLayoutInflater().inflate(R.layout.frammento_corsi, null, true);

Search listview using filter

I have a project in android studio that loads data from an online database and put that data in a listview. Above the listview there is an EditText that i want to search the listview with the value that i write inside. I tried to adapt this tutorial to mine but i get many errors and crashes that i cannot fix becaue i am a noob. Can you help me to adapt the tutorial to my project please? Below is my code without the search filter. If you want i can upload my try with the errors. Thank you in advance!
AllStudents.java:
public class AllStudents extends AppCompatActivity {
ListView StudentListView;
ProgressBar progressBar;
String HttpUrl = "http://sissy-nickels.000webhostapp.com/AllStudentData.php";
List<String> IdList = new ArrayList<>();
String LessonName;
HttpParse httpParse = new HttpParse();
ProgressDialog pDialog;
String FinalJSonObject;
HashMap<String,String> ResultHash = new HashMap<>();
String ParseResult ;
List<Student> studentList;
#Override
public void onBackPressed()
{
super.onBackPressed();
startActivity(new Intent(AllStudents.this, AddStudent.class));
finish();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_allstudents);
StudentListView = (ListView)findViewById(R.id.listview2);
progressBar = (ProgressBar)findViewById(R.id.progressBar);
LessonName = getIntent().getStringExtra("Lesson");
HttpWebCall(LessonName);
//Adding ListView Item click Listener.
StudentListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
Intent intent = new Intent(AllStudents.this,SingleStudent.class);
// Sending ListView clicked value using intent.
intent.putExtra("ListViewValue", IdList.get(position).toString());
startActivity(intent);
//Finishing current activity after open next activity.
finish();
}
});
}
public void HttpWebCall(final String LessonName){
class HttpWebCallFunction extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = ProgressDialog.show(AllStudents.this,"Loading Data",null,true,true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
pDialog.dismiss();
//Storing Complete JSon Object into String Variable.
FinalJSonObject = httpResponseMsg ;
//Parsing the Stored JSOn String to GetHttpResponse Method.
new GetHttpResponse(AllStudents.this).execute();
}
#Override
protected String doInBackground(String... params) {
ResultHash.put("LessonName",params[0]);
ParseResult = httpParse.postRequest(ResultHash, HttpUrl);
return ParseResult;
}
}
HttpWebCallFunction httpWebCallFunction = new HttpWebCallFunction();
httpWebCallFunction.execute(LessonName);
}
// JSON parse class started from here.
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
public Context context;
public GetHttpResponse(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
try
{
if(FinalJSonObject != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonObject);
JSONObject jsonObject;
Student student;
studentList = new ArrayList<Student>();
for(int i=0; i<jsonArray.length(); i++)
{
jsonObject = jsonArray.getJSONObject(i);
student = new Student();
// Adding Student Id TO IdList Array.
IdList.add(jsonObject.getString("id").toString());
//Adding Student Name.
student.StudentName = jsonObject.getString("Regnum").toString();
studentList.add(student);
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
progressBar.setVisibility(View.GONE);
StudentListView.setVisibility(View.VISIBLE);
ListAdapter adapter = new ListAdapter(studentList, context);
StudentListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}}
ListAdapter.java
public class ListAdapter extends BaseAdapter {
Context context;
List<Student> valueList=null;
public ListAdapter(List<Student> listValue, Context context)
{
this.context = context;
this.valueList = listValue;
if(valueList==null){
valueList = new ArrayList<>();
}
}
#Override
public int getCount()
{
return this.valueList.size();
}
#Override
public Object getItem(int position)
{
return this.valueList.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewItem viewItem;
convertView = null;
if(convertView == null)
{
viewItem = new ViewItem();
LayoutInflater layoutInfiater = (LayoutInflater)this.context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = layoutInfiater.inflate(R.layout.listviewitem, null);
viewItem.TextViewStudentName = (TextView)convertView.findViewById(R.id.textView1);
convertView.setTag(viewItem);
}
else
{
viewItem = (ViewItem) convertView.getTag();
}
viewItem.TextViewStudentName.setText(valueList.get(position).StudentName);
return convertView;
}}class ViewItem{ TextView TextViewStudentName;}
Student.java:
public class Student {
public String StudentName ;}
listview.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/gradient"
android:padding="15dp">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:textColor="#android:color/holo_blue_dark"
android:textSize="24dp" />
avtivity_allstudents.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_show_all_students"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.djale.login_register.AllStudents"
android:background="#drawable/gradient"
>
<EditText
android:id="#+id/search"
android:layout_width="250dp"
android:layout_height="30dp"
android:layout_alignParentEnd="true"
android:layout_alignParentStart="true"
android:background="#11000000"
android:ems="10"
android:drawableLeft="#drawable/ic_search_black_24dp"
android:hint=" Search by reg. number"
android:inputType="textPersonName"
android:textColorHint="#android:color/holo_blue_dark"
android:textSize="18sp" />
<ListView
android:id="#+id/listview2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_below="#+id/search" />
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="visible"
/>
You can do like this :
search=(EditText)findviewById(R.id.search);
search.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
searchList=new ArrayList<>();
for(studentList name: String){
if(name.toLowerCase().contains(editable.toString().toLowerCase())){
searchList.add(name);
}
}
//clear data in adapter
//add searchList to your adapter
}
});
You can add TextChangedListener to your search box (which is a EditText). In onTextChanged(), filter list & update ListView accordingly.
In AllStudents.java, try making these changes:
public class AllStudents extends AppCompatActivity {
.....
#Override
protected void onCreate(Bundle savedInstanceState) {
....
StudentListView.setOnItemClickListener(...)
// add TextChangedListener to search box.
// It listens for user's entered text & filter students' list by name
EditText searchEditText = (EditText) findViewById(R.id.search);
searchEditText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged (CharSequence s, int start, int count, int after) {
}
// when text is entered in search box, filter list by search text
#Override
public void onTextChanged(CharSequence cs, int start, int before, int count) {
filterStudents(cs);
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
// check student's name whether contain text entered in search box
private void filterStudents (CharSequence cs) {
List<Student> filteredList = new ArrayList<>();
if (TextUtils.isEmpty(cs)) {
// no text is entered for search, do nothing
return;
}
// build new student list which filtered by search text.
for (Student student : studentList) {
if (student.StudentName.contains(cs)) {
filteredList.add(student);
}
}
// show filtered list in listview
ListAdapter adapter = new ListAdapter(filteredList, this);
StudentListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}

Custom Adapter on applying on list view

I have made a custom Adapter and populate it with the data. I have used Logcat to see whether the array i'm passing to custom Adapter class contains the data and it does.
The error i got is following. It occurs when this CategoryBlog is created. Activity is created but it does not contain list view
exception: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
'mainblogpost' contains the array with all the data i want to populate with.
'MainListActivityAdapter' is the Adapter Class.
'Category_Blogs' is the class where i want to set the list view.
Category_Blog.java
I don't add import statement. there is no error in it
public class Category_Blogs extends AppCompatActivity implements AbsListView.OnItemClickListener {
public static final String TAG = MainActivity.class.getSimpleName();
public final static String EXTRA_MESSAGE = "com.example.talha.appforblog.MESSAGE";
List<StackOverflowXmlParser.Entry> mainBlogPost = new ArrayList<StackOverflowXmlParser.Entry>();
private ListAdapter mAdapter;
private AbsListView mListView;
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category__blogs);
//Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
//setSupportActionBar(toolbar);
Intent intent = getIntent();
String message = intent.getStringExtra(Tab2.EXTRA_MESSAGE);
String link = message.trim() + "?feed=titles";
Log.d("ye category click krne par next activity me ye link bnta hy parsing ke liye",link);
loadPage(link);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_category__blogs, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void loadPage(String link) {
Log.d(TAG, "loadpage me a gae nh");
// if((sPref.equals(ANY)) && (wifiConnected || mobileConnected)) {
new DownloadXmlTask(this).execute(link);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
private class DownloadXmlTask extends AsyncTask<String, Void, List<StackOverflowXmlParser.Entry>> {
private Context mContext;
public DownloadXmlTask(Context context) {
mContext = context;
}
#Override
protected List<StackOverflowXmlParser.Entry> doInBackground(String... urls) {
try {
return loadXmlFromNetwork(urls[0]);
} catch (Exception e) {
Log.d("test", "" + e);
}
return null;
}
#Override
protected void onPostExecute(List<StackOverflowXmlParser.Entry> results) {
if (results != null) {
try {
String title, link, image, pubDate;
Log.d("test", "onpost");
// custom array adapter
ArrayList<HashMap<String, String>> blogPosts = new ArrayList<HashMap<String, String>>();
for (StackOverflowXmlParser.Entry result : results) {
title = result.title;
link = result.link;
image = result.image;
pubDate = result.pubDate;
HashMap<String, String> blogPost = new HashMap<String, String>();
blogPost.put("link", link);
blogPost.put("title", title);
blogPost.put("image", image);
blogPost.put("pubDate", pubDate);
blogPosts.add(blogPost);
}
// copying to main item List array
for (int i = 0; i < results.size(); i++) {
mainBlogPost.add(results.get(i));
}
Log.d("fff", results.get(1).pubDate);
MainListActivityAdapter mAdapter =
new MainListActivityAdapter(Category_Blogs.this, mainBlogPost);
listView.setAdapter(mAdapter);
//((AdapterView<ListAdapter>) mListView).setAdapter(mAdapter);
// Set OnItemClickListener so we can be notified on item clicks
mListView.setOnItemClickListener(Category_Blogs.this);
}
catch (Exception e){
Log.d("test", "exception: "+e);
}
}
}
private List<StackOverflowXmlParser.Entry> loadXmlFromNetwork(String urlString) throws XmlPullParserException, IOException {
InputStream stream = null;
// Instantiate the parser
StackOverflowXmlParser stackOverflowXmlParser = new StackOverflowXmlParser();
List<StackOverflowXmlParser.Entry> entries = null;
String title = null;
String url = null;
try {
//opening the connection and fetching
stream = downloadUrl(urlString);
entries = stackOverflowXmlParser.parse(stream);
// Makes sure that the InputStream is closed after the app is
// finished using it.
} catch (Exception e) {
Log.d("test", "" + e);
} finally {
if (stream != null) {
stream.close();
}
}
for (StackOverflowXmlParser.Entry entry : entries) {
Log.d("aaa",entry.pubDate);
}
return entries;
}
private InputStream downloadUrl(String urlString) throws IOException {
java.net.URL url = new java.net.URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
return conn.getInputStream();
}
}
}
MainListActivityAdapter.java
public class MainListActivityAdapter extends BaseAdapter {
private Activity activity;
List<StackOverflowXmlParser.Entry> mainBlogPost = new ArrayList<StackOverflowXmlParser.Entry>();
private static LayoutInflater inflater = null;
public MainListActivityAdapter(Activity a, List<StackOverflowXmlParser.Entry> main) {
activity = a;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mainBlogPost = main;
}
public int getCount() {
return mainBlogPost.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
Log.d("test", "fetching" + position);
String tit = mainBlogPost.get(position).title;
String cate = mainBlogPost.get(position).pubDate;
String pub = mainBlogPost.get(position).pubDate;
String image_url = "http://download.androidhive.info/img/btn_fb_login.png";
if (convertView == null)
vi = inflater.inflate(R.layout.list_row, null);
TextView title = (TextView) vi.findViewById(R.id.title); // title
TextView cat = (TextView) vi.findViewById(R.id.category); // category
ImageView image = (ImageView) vi.findViewById(R.id.list_image); // image
TextView publish = (TextView) vi.findViewById(R.id.pubDate); // publish date
// Setting all values in listview
title.setText(tit);
cat.setText(cate);
publish.setText(pub);
Glide.with(activity)
.load(image_url)
.into(image);
return vi;
}
}
Activity_category_blog.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent"
android:layout_height="wrap_content" tools:context="com.example.talha.test_fragement.Category_Blogs"
xmlns:ads="http://schemas.android.com/apk/res-auto">
<include layout="#layout/tool_bar" />
<FrameLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#layout/tool_bar">
<ListView android:id="#android:id/list" android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/adView" android:divider="#b5b5b5"
android:dividerHeight="1dp"
android:layout_alignParentBottom="true"
/>
<TextView android:id="#android:id/empty" android:layout_width="match_parent"
android:layout_height="match_parent" android:gravity="center"
android:layout_gravity="right|top" />
</FrameLayout>
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category__blogs);
listView = (ListView) findViewById(R.id.lvID);//where lvID is id from your listview placed in activity_category__blogs layout.
You fail to initialize the listview.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category__blogs);
//Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
**listView = (ListView) findViewById(R.id.list);**
//setSupportActionBar(toolbar);
Intent intent = getIntent();
String message = intent.getStringExtra(Tab2.EXTRA_MESSAGE);
String link = message.trim() + "?feed=titles";
Log.d("ye category click krne par next activity me ye link bnta hy parsing ke liye",link);
loadPage(link);
}

using checkbox in android for displaying toast message in listview

What i have done::I have got s list of items from server & display in listview
each row of list has a checkbox in it, list view also has a button on top as show in figure below
What i need to do ::
out of six rows if i select three rows using checkbox on click of
button next showed in figure i must be able to display the toast
message of selected elements
I don't know how to fill the parts of onclick function of
checkButtonClick() in code
ListViewAdapterForAtomicListItemtype.java
public class ListViewAdapterForAtomicListItemtype extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapterForAtomicListItemtype(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView name;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.listview_item_for_atomic_list_item_type, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
name = (TextView) itemView.findViewById(R.id.textView_id_atomic_list_item_type);
// Capture position and set results to the TextViews
name.setText(resultp.get(MainActivity.NAME));
return itemView;
}
}
listview_main_atomic_list_itemtype.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" >
<ListView
android:id="#+id/listview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/button1" />
<Button
android:id="#+id/button_of_listview_main_atomic_list_itemtype_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="DisplayItems" />
</RelativeLayout>
listview_item_for_atomic_list_item_type.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" >
<TextView
android:id="#+id/textView_id_atomic_list_item_type"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="17dp"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<CheckBox
android:id="#+id/checkBox_atomic_list_item_type_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true" />
</RelativeLayout>
BLD_IndividualListOfItems_Starters.java
public class BLD_IndividualListOfItems_Starters extends Activity{
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapterForAtomicListItemtype adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String NAME = "rank";
String TYPE_FILTER;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main_atomic_list_itemtype);
TYPE_FILTER = getIntent().getExtras().getString("key_title");
Log.v("---- Value-Start---", TYPE_FILTER);
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(BLD_IndividualListOfItems_Starters.this);
// Set progressdialog title
//mProgressDialog.setTitle("Fetching the information");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
String newurl = "?" + "Key=" + TYPE_FILTER;
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions.getJSONfromURL("http://54.218.73.244:7005/RestaurantAtomicListItemType/"+newurl);
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("restaurants");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put(MainActivity.NAME, jsonobject.getString("MasterListMenuName"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapterForAtomicListItemtype(BLD_IndividualListOfItems_Starters.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
private void checkButtonClick() {
Button myButton = (Button) findViewById(R.id.button_of_listview_main_atomic_list_itemtype_id);
myButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
}
{EDIT}
BLD_IndividualListOfItems_Starters.java
public class BLD_IndividualListOfItems_Starters extends Activity{
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapterForAtomicListItemtype adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String NAME = "rank";
String TYPE_FILTER;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main_atomic_list_itemtype);
TYPE_FILTER = getIntent().getExtras().getString("key_title");
Log.v("---- Value-Start---", TYPE_FILTER);
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(BLD_IndividualListOfItems_Starters.this);
// Set progressdialog title
//mProgressDialog.setTitle("Fetching the information");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
String newurl = "?" + "Key=" + TYPE_FILTER;
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions.getJSONfromURL("http://54.218.73.244:7005/RestaurantAtomicListItemType/"+newurl);
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("restaurants");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put(MainActivity.NAME, jsonobject.getString("MasterListMenuName"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapterForAtomicListItemtype(BLD_IndividualListOfItems_Starters.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
private void checkButtonClick() {
Button myButton = (Button) findViewById(R.id.button_of_listview_main_atomic_list_itemtype_id);
myButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
StringBuilder result = new StringBuilder();
for(int i=0;i<arraylist.size();i++)
{
if(adapter.mCheckStates.get(i)==true)
{
result.append(arraylist.get(i).get(MainActivity.NAME));
result.append("\n");
}
}
Toast.makeText(BLD_IndividualListOfItems_Starters.this, result, 1000).show();
}
});
}
}
ListViewAdapterForAtomicListItemtype.java
public class ListViewAdapterForAtomicListItemtype extends BaseAdapter implements android.widget.CompoundButton.OnCheckedChangeListener{
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
HashMap<String, String> resultp = new HashMap<String, String>();
SparseBooleanArray mCheckStates;
public ListViewAdapterForAtomicListItemtype(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
mCheckStates = new SparseBooleanArray(data.size());
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView name;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.listview_item_for_atomic_list_item_type, parent, false);
// Get the position
CheckBox chkSelect =(CheckBox) itemView.findViewById(R.id.checkBox_atomic_list_item_type_id);
chkSelect.setTag(position);
chkSelect.setChecked(mCheckStates.get(position, false));
chkSelect.setOnCheckedChangeListener(this);
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
name = (TextView) itemView.findViewById(R.id.textView_id_atomic_list_item_type);
// Capture position and set results to the TextViews
name.setText(resultp.get(MainActivity.NAME));
return itemView;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
you can also use for MULTIPLE CHOICE OF LISTVIEW.
StringBuilder result;
After Click on Button you can do this:
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
result = new StringBuilder();
for (int i = 0; i < arraylist.size(); i++) {
if (adapter.mysparse.get(i) == true) {
result.append(arraylist.get(i).get(MainActivity.NAME));
result.append("\n");
}
}
Intent n = new Intent(MainActivity.this, DisplayActivity.class);
n.putExtra("buffer", result.toString());
startActivity(n);
}
});
And in your DisplayActivity you can do like this:
package com.example.singleitemlistview;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class DisplayActivity extends Activity {
ListView lv;
ArrayList<String> myList;
String myName;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
Intent n = getIntent();
myName = n.getStringExtra("buffer");
myList = new ArrayList<String>();
lv = (ListView) findViewById(R.id.listViewData);
myList.add(myName);
lv.setAdapter(new ArrayAdapter<String>(DisplayActivity.this,
android.R.layout.simple_list_item_1, myList));
}
}
Use a SparseBooleanArray.
More info #
https://groups.google.com/forum/?fromgroups#!topic/android-developers/No0LrgJ6q2M
In your adapter implement CompoundButton.OnCheckedChangeListener
public class ListViewAdapterForAtomicListItemtype extends BaseAdapter implements CompoundButton.OnCheckedChangeListener
{
SparseBooleanArray mCheckStates;
public ListViewAdapterForAtomicListItemtype(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
mCheckStates = new SparseBooleanArray(data.size());
}
Then in getView
CheckBox chkSelect =(CheckBox) item.findViewById(R.id.CheckBox
android:id="#+id/checkBox_atomic_list_item_type_id");
chkSelect.setTag(position);
chkSelect.setChecked(mCheckStates.get(position, false));
chkSelect.setOnCheckedChangeListener(this);
Override the following methods
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
In onClick of Button
StringBuilder result = new StringBuilder();
for(int i=0;i<arraylist.size();i++)
{
if(adapter.mCheckStates.get(i)==true)
{
result.append(arrayList.get(i).get(MainActivtiy.Name));
result.append("\n");
}
}
Toast.makeText(ActivityName.this, result, 1000).show();
Note:
It is better to use a ViewHolder Pattern.
http://developer.android.com/training/improving-layouts/smooth-scrolling.html
StringBuffer result = new StringBuffer();
result.append("TEXTVIEW 1 : ").append(chkbox1.isChecked());
result.append("\nTEXTVIEW 2 : ").append(chkbox2.isChecked());
result.append("\nTEXTVIEW 3 :").append(chkbox3.isChecked());
//and so on.........
Toast.makeText(MyAndroidAppActivity.this, result.toString(),
Toast.LENGTH_LONG).show();
I think this wat you need. Just update you got solution or not. this code must be in the next button onclickListener.
Try it out nd vote and ping if works. before tat update wats happening.
ADDED:
mainListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String ss;
ss=(String) ((TextView) view).getText();
This code is to check which item is clicked.
by this with lenght of the list , check in for loop to check whether its checkbox is clicked or not.
Aftert that you can easily append that list of checked items.
Never tried but should work..you can use following code inside onClick() to get CheckBox status for each row.
if (adapter!=null&&adapter.getCount()>0) {
for(int i=0;i<adapter.getCount();i++){
View view=(View)adapter.getItem(i);
CheckBox chk=(CheckBox)view.findViewById(R.id.checkbox);
TextView txt=(TextView)view.findViewById(R.id.textview);
if (chk.isChecked()) {
//do something here
}
}
}

How to get First and Second Level List using JSON only

I am getting data into ListView using JSON, but for the first Level List, i am using static code, in short first level list not getting using JSON, see below code using to show first level List.
Category Screen (showing data in a Static way)
Product Screen (getting data using JSON)
CategoryActivity.java:
public class CategoriesActivity extends Activity implements OnItemClickListener {
ListView lview3;
ListViewCustomAdapter adapter;
private ArrayList<Object> itemList;
private ItemBean bean;
ImageButton checkOut;
ImageButton back;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menus);
prepareArrayLits();
lview3 = (ListView) findViewById(R.id.listView1);
adapter = new ListViewCustomAdapter(this, itemList);
lview3.setAdapter(adapter);
lview3.setOnItemClickListener(this);
}
private static final int Sony = 0;
private static final int Panasonic = 1;
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
// Set up different intents based on the item clicked:
switch (position)
{
case Sony:
Intent intent1 = new Intent(CategoriesActivity.this, ProductsActivity.class);
intent1.putExtra("category", "Sony");
startActivity(intent1);
break;
case Panasonic:
Intent intent2 = new Intent(CategoriesActivity.this, ProductsActivity.class);
intent2.putExtra("category", "Panasonic");
startActivity(intent2);
break;
default:
break;
}
}
public void prepareArrayLits()
{
itemList = new ArrayList<Object>();
AddObjectToList( "Sony" );
AddObjectToList( "Panasonic" );
}
// Add one item into the Array List
public void AddObjectToList(String title)
{
bean = new ItemBean();
bean.setTitle(title);
itemList.add(bean);
}
}
ItemBean.java:
public class ItemBean
{
String title;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
ListViewCustomAdapter.java:
public class ListViewCustomAdapter extends BaseAdapter{
ArrayList<Object> itemList;
public Activity context;
public LayoutInflater inflater;
public ListViewCustomAdapter(Activity context,ArrayList<Object> itemList) {
super();
this.context = context;
this.itemList = itemList;
this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
// TODO Auto-generated method stub
return itemList.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return itemList.get(position);
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public static class ViewHolder
{
TextView txtViewTitle;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
if(convertView==null)
{
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.listrow_categories, null);
holder.txtViewTitle = (TextView) convertView.findViewById(R.id.title);
convertView.setTag(holder);
}
else
holder=(ViewHolder)convertView.getTag();
ItemBean bean = (ItemBean) itemList.get(position);
holder.txtViewTitle.setText(bean.getTitle());
return convertView;
}
}
and to get data into Second Level List (i.e: Products List), using below code,
ProductsActivity.java:-
public class ProductsActivity extends Activity {
static String URL = "http://10.0.2.2/android/test.json";
static String KEY_CATEGORY = "item";
static final String KEY_TITLE = "ProductName";
ListView list;
LazyAdapter adapter;
/** Called when the activity is first created. */
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menus);
final ArrayList<HashMap<String, String>> itemsList = new ArrayList<HashMap<String, String>>();
list = (ListView) findViewById(R.id.listView1);
adapter = new LazyAdapter(this, itemsList);
list.setAdapter(adapter);
if (isNetworkAvailable()) {
new MyAsyncTask().execute();
} else {
AlertDialog alertDialog = new AlertDialog.Builder(ProductsActivity.this).create();
alertDialog.setMessage("The Internet connection appears to be offline.");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
}
private boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
return (info != null);
}
class MyAsyncTask extends
AsyncTask<String, Integer, ArrayList<HashMap<String, String>>> {
private ProgressDialog progressDialog = new ProgressDialog(
ProductsActivity.this);
#Override
protected void onPreExecute() {
progressDialog.setMessage("Loading, Please wait.....");
progressDialog.show();
}
final ArrayList<HashMap<String, String>> itemsList = new ArrayList<HashMap<String, String>>();
#Override
protected ArrayList<HashMap<String, String>> doInBackground(
String... params) {
HttpClient client = new DefaultHttpClient();
// Perform a GET request for a JSON list
HttpUriRequest request = new HttpGet(URL);
// Get the response that sends back
HttpResponse response = null;
try {
response = client.execute(request);
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Convert this response into a readable string
String jsonString = null;
try {
jsonString = StreamUtils.convertToString(response.getEntity()
.getContent());
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Create a JSON object that we can use from the String
JSONObject json = null;
try {
json = new JSONObject(jsonString);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
JSONArray jsonArray = json.getJSONArray(KEY_CATEGORY);
for (int i = 0; i < jsonArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jsonObject = jsonArray.getJSONObject(i);
map.put("KEY", String.valueOf(i));
map.put(KEY_TITLE, jsonObject.getString(KEY_TITLE));
itemsList.add(map);
}
return itemsList;
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return null;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
list = (ListView) findViewById(R.id.listView1);
adapter = new LazyAdapter(ProductsActivity.this, itemsList);
list.setAdapter(adapter);
this.progressDialog.dismiss();
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
}
}
LazyAdapter.java:
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.listrow_products, null);
TextView title = (TextView)vi.findViewById(R.id.title);
HashMap<String, String> item = new HashMap<String, String>();
item = data.get(position);
// Setting all values in listview
title.setText(item.get(ProductsActivity.KEY_TITLE));
return vi;
}
}
StreamUtils.java:-
public class StreamUtils {
public static String convertToString(InputStream inputStream) throws IOException {
if (inputStream != null) {
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 1024);
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
inputStream.close();
}
return writer.toString();
} else {
return "";
}
}
}
Question:
How to get First Level List by using JSON, not by writing static code like i have written in my existing program?
test.json:
{
"Sony": [{
"ProductID": "1",
"ProductName": "Sony - LED TV"
}, {
"ProductID": "2",
"ProductName": "Sony - Laptop"
}],
"Panasonic": [{
"ProductID": "1",
"ProductName": "Panasonic - LED TV"
}, {
"ProductID": "2",
"ProductName": "Panasonic - Laptop"
}]
}
You can write an asynctask for generating first level list using json parsing. Now, in your activity, you can have a datastructure like map, arraylist etc for holding the first level list. In onCreate of the application, you can call your asynctask to do json parsing can fill you local data structure which you can then use to show first level list.
Or
you can redesign your app in a simpler way. Keep a single listview with an adapter. And on clicking any item in the list, you can change the dataset of your listview.
Something like this:
public void onItemClick(AdapterView parent, View view,
int position, long id) {
if(isLevel1Column1) {
mAdapter_1.setListData(mSubMenu1);
isLevel1Column1 = false;
mAdapter_1.notifyDataSetChanged();
I have achieved something like this before. in my case also, i used lazyloading code :)
It seems you are getting the json from the web service. The better approach will be to actually modify your json response in a way which will give the category name and array both. At present the way your json is structured is probably not correct. Now, you have only two products i.e. sony and panasonic but that may increase. So, better modify your json in a way which gives category name and its listing probably in a way as mentioned below :
[
{
"categoryName" : "Sony",
"categoryList" : [{"ProductID": "1",
"ProductName": "Sony - LED TV"},
{"ProductID": "2",
"ProductName": "Sony - Laptop"}]
},
{
"categoryName" : "Panasonic",
"categoryList" : [{"ProductID": "1",
"ProductName": "Panasonic - LED TV"},
{"ProductID": "2",
"ProductName": "Panasonic - Laptop"}]
}
]
This way you can get the names dynamically as well the listing. Hope this helps you out.
If you just want to populate the listview with static strings then you can create a string array and use the code as mentioned below :
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, values);
listView.setAdapter(adapter);
As per my understanding you require ExpandableListView which contains Parent at its first view .. When you click on any parent you get list of child under it.
Dynamically populate parent and child to ExpandableListView using key name for parent and its object as child from JSON... ( Just change api from which you need to access data ).
Your main class where you require to show all stuffs
------------------------------------------------------
public class ViewProfileService extends Activity{
/** Define Async Task variables over here ..vvvv*/
HttpClient httpclient;
HttpGet httpget;
HttpResponse httpresponse;
HttpResponse hhttpresponse;
JSONObject myJsonObject = null;
JSONArray myJsonArray = null;
String myJsonString = "";
JSONObject nmyJsonObject = null;
JSONArray nmyJsonArray = null;
String nmyJsonString = "";
String service;
String name;
ServiceList sl;
String[] head;
//private ProgressDialog pDialog;
// private ArrayList<ServiceList> m_ArrayList = null;
///////////////////////////////////////////////////ArrayList<String[]> header = new ArrayList<String[]>();
/** Expandable list credentials */
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
String bo_uid;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.view_profile_service);
SharedPreferences sp = getSharedPreferences("all_id", 0);
bo_uid = sp.getString("bo_uid", "");
new BussinessOwnerHttpAsyncTask().execute();
//setGroupIndicatorToRight();
/*// Create a Drawable object with states
Drawable icon =
this.getResources().getDrawable(R.drawable.expander_group);
// Set the newly created Drawable object as group indicator.
// Now you should be seeing your icons as group indicators.
getExpandableListView().setGroupIndicator(icon);*/
}
class BussinessOwnerHttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
/*pDialog = new ProgressDialog(getParent());
pDialog.setMessage("Please wait ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();*/
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
StaticVars sv = new StaticVars();
// Starting Async Task work over here ...
HttpClient httpclient = new DefaultHttpClient();
#SuppressWarnings("static-access")
String myUrl = "your url " ;//set you url over here
myUrl = myUrl.replaceAll("\n", "");
myUrl = myUrl.replaceAll(" ", "%20");
Log.d("checkurl", myUrl);
HttpGet httpget = new HttpGet(myUrl.trim());
try {
httpresponse = httpclient.execute(httpget);
System.out.println("httpresponse" + httpresponse);
Log.i("response", "Response" + httpresponse);
InputStream is = httpresponse.getEntity().getContent();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String recievingDataFromServer = null;
while ((recievingDataFromServer = br.readLine()) != null) {
Log.i("CHECK WHILE", "CHECK WHILE");
sb.append(recievingDataFromServer);
}
myJsonString = sb.toString();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#SuppressWarnings("unchecked")
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// pDialog.dismiss();
if (myJsonString.length() > 0) {
try {
myJsonObject = new JSONObject(myJsonString);
JSONObject object = myJsonObject.getJSONObject("services");
Iterator<String> iterate = object.keys();
//m_ArrayList = new ArrayList<ServiceList>();
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
List<String> toptodown = null;
while(iterate.hasNext()){
service = iterate.next();
Log.d("goging", service);
listDataHeader.add(service);
myJsonArray = object.getJSONArray(service);
toptodown = new ArrayList<String>();
for (int i = 0; i < myJsonArray.length(); i++) {
JSONObject okay = myJsonArray.getJSONObject(i);
name = okay.getString("name");
Log.d("goging","Name is: " + name);
toptodown.add(name);
}
listDataChild.put(service, toptodown);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
start();
}
}
public void start() {
// TODO Auto-generated method stub
expListView = (ExpandableListView) findViewById(R.id.lvExp);
listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);
// setting list adapter
expListView.setAdapter(listAdapter);
}
}
your view_profile_service.xml file used in ViewProfileService.java class
-----------------------------------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ExpandableListView
android:id="#+id/lvExp"
android:layout_height="match_parent"
android:layout_width="match_parent"/>
</LinearLayout>
your ExpandableListAdapter.java class ..
-------------------------------------
import java.util.HashMap;
import java.util.List;
import com.app.ruzanamah.R;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> _listDataChild;
public ExpandableListAdapter(Context context, List<String> listDataHeader,
HashMap<String, List<String>> listChildData) {
this._context = context;
this._listDataHeader = listDataHeader;
this._listDataChild = listChildData;
}
#Override
public Object getChild(int groupPosition, int childPosititon) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.get(childPosititon);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final String childText = (String) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_item, null);
}
TextView txtListChild = (TextView) convertView
.findViewById(R.id.lblListItem);
txtListChild.setText(childText);
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.size();
}
#Override
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
#Override
public int getGroupCount() {
return this._listDataHeader.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.lblListHeader);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
your list_item.xml file used in ExpandableListAdapter.java class
---------------------------------------------------------------
<?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="55dip"
android:orientation="vertical" >
<TextView
android:id="#+id/lblListItem"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="17dip"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:paddingLeft="?android:attr/expandableListPreferredChildPaddingLeft" />
</LinearLayout>
your list_group.xml file used in ExpandableListAdapter.java class
-------------------------------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="8dp"
>
<!-- android:background="#000000" -->
<TextView
android:id="#+id/lblListHeader"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft"
android:textSize="17dp"/>
</LinearLayout>
Above mentioned contains all you need to perform your stuff very efficiently..
Enjoy .. !

Categories

Resources