Android: Passing HashMap between Activity and Fragments - android

I am a newbie to Android development, and I have encountered a halt in my application development. I hope somebody can help me out here.
I have an activity named JSONActivity and inside JSONActivity, I extract JSON data from a web url, and store it into 3 HashMaps, depending on the type of data.
I would like to pass a HashMap to 3 different Fragments. I'll start with just doing it for one fragment however, I cannot seem to pass the data.
Can somebody point out what I am doing wrong, and what I can do to fix it?
I can assure that the json extraction works fine, because the data can be rendered using a Toast
JSONActivity.java
package com.example.json;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.IOException;
import android.app.Activity;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.util.Log;
import android.os.AsyncTask;
public class JSONActivity extends Activity {
HashMap<Integer,String> imageList = new HashMap<Integer,String>();
HashMap<Integer,String> textList = new HashMap<Integer,String>();
HashMap<Integer,String> otherList = new HashMap<Integer,String>();
private static final String ID = "id";
private static final String TYPE = "type";
private static final String DATA = "data";
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
} else {
Log.e("JSON", "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
private class ReadJSONFeedTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
return readJSONFeed(urls[0]);
}
protected void onPostExecute(String result) {
try {
JSONArray jsonArray = new JSONArray(result);
Log.i("JSON", "Number of json items: " +
jsonArray.length());
//---print out the content of the json feed---
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int id = jsonObject.getInt(ID);
String type = jsonObject.getString(TYPE);
String data = jsonObject.getString(DATA);
if(type.equals("text"))
textList.put(id,data);
else if(type.equals("other"))
otherList.put(id,data);
else if(type.equals("image"))
imageList.put(id,data);
// Toast.makeText(getBaseContext(), jsonObject.getString("type") +
// " - " + jsonObject.getString("data"), Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new ReadJSONFeedTask().execute(
"sample url (not shown in this post)");
}
}
Fragment1.java:
package com.example.json;
import java.util.HashMap;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class fragment1 extends ListFragment {
#SuppressWarnings("unchecked")
public HashMap<Integer,String> textList =
(HashMap<Integer, String>) getArguments().getSerializable("textList");
public String[] vals = new String[textList.size()];
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
for(int i = 0; i < textList.size(); i++)
vals[i] = (String)textList.values().toArray()[i];
return inflater.inflate(R.layout.fragment1, container, false);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, vals));
}
public void onListItemClick(ListView parent, View v, int position, long id)
{
Toast.makeText(getActivity(),
"You have selected " + vals[position], Toast.LENGTH_SHORT).show();
}
}
fragment1.xml:
<?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" >
<ListView
android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:drawSelectorOnTop="false" />
</LinearLayout>
main.xml:
<?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="horizontal" >
<fragment
android:id="#+id/fragment1"
android:name="com.example.json.Fragment1"
android:layout_width="0dp"
android:layout_height="200dp"
android:layout_weight="0.5" />
<fragment
android:id="#+id/fragment2"
android:name="com.example.json.Fragment1"
android:layout_width="0dp"
android:layout_height="300dp"
android:layout_weight="0.5" />
</LinearLayout>

You need to define a setter method in your fragments which will set the HashMap property of fragment and display it to the user. After that when you done parsing json data call it like this:
((Fragment1) getSupportFragmentManager.findFragmentById(R.id.fragment1)).setAndDisplayJSONDataMethod(valuesToShow);
and setAndDisplayJSONDataMethod method will be something like this:
public void setAndDisplayJSONDataMethod(HashMap<Integer, String> valuesToShow) {
String[] vals = new String[textList.size()];
for(int i = 0; i < textList.size(); i++)
vals[i] = (String)valuesToShow.values().toArray()[i];
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, vals));
}
For now it doesn't work cause you're trying to get/set your list data in a wrong place and in a wrong time. Read about Fragments and Fragments/Actvities lifecycles.

In java, strings have to be compared with equals or equalsIgnoreCase
if(type.equals("text"))
textList.put(id,data);
else if(type.equals("other"))
otherList.put(id,data);
else if(type.equals("image"))
imageList.put(id,data);

Related

Need help regarding integrating android functions with premade views

I'm just new to android and java and i m trying to build a sample android application.
I picked up application view from androhive looks like google+ app
and made my function following to many tutorials online
but i'm unable to integrate them.
here are my codes
Here is my fragment sample which is used in switching activity using sidebar
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MHEFragment extends Fragment {
public MHEFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
return rootView;
}
}
Heres my function os listview
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
private String jsonResult;
private String url = "http://192.168.129.1/1.php";
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView1);
accessWebService();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
ListDrwaer();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void ListDrwaer() {
List<Map<String, String>> storyList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("story");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("story_name");
String number = jsonChildNode.getString("story_id").toString();
String outPut = number + "-" + name;
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View name, int position,
long number) {
Intent intnt = new Intent(getApplicationContext(), Tester.class);
String deta = adapter.getItemAtPosition(position).toString();
String myStr = deta.replaceAll( "[^\\d]", "" );
intnt.putExtra(EXTRA_MESSAGE,myStr);
startActivity(intnt);
}
});
storyList.add(createStory("stories", outPut));
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
SimpleAdapter simpleAdapter = new SimpleAdapter(this, storyList,
android.R.layout.simple_list_item_1,
new String[] { "stories" }, new int[] { android.R.id.text1 });
listView.setAdapter(simpleAdapter);
}
private HashMap<String, String> createStory(String name, String number) {
HashMap<String, String> storyNameNo = new HashMap<String, String>();
storyNameNo.put(name, number);
return storyNameNo;
}
}
How can i integrate my listview in above fragment?
If you want ListView in fragment then you'd be better off using your Fragment which would subclass ListFragment.
And the onCreateView() from ListFragment will return a ListView that you can populate.
http://developer.android.com/reference/android/app/ListFragment.html
http://www.vogella.com/tutorials/AndroidListView/article.html#listfragments
For Fragments, if you want a separate ListView and more in one fragment, it'l help if you go through:
http://www.easyinfogeek.com/2013/07/full-example-of-using-fragment-in.html
..for what is more to the layout and calling onCreateView()
Also, (not a part of the question, but from & for your code) if it helps, i'd suggest
Use a for each loop where you can instead of for(;;)
(in your case at: for each json child node in json main node)
http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html
How does the Java 'for each' loop work?

How to display a JSON from web service in Android List

I am trying since yesterday to make my application take some JSON data generated by a PHP file and then display this data in a list view.
The PHP File is encoding data using encode method:
echo json_encode($results);
Viewed from the browsers view source the JSON generated by file.php looks like this:
["","CSD1939","CSD1939"]
The JSONLint (A great tool) validates this as a correct JSON format.
When I am trying to use my application to fetch this JSON from the webservice I am fetching it as a String first but I am having trouble passing it to the adapter and making it display correctly.
I only managed until now to create a listview that displays a String Array.
What is the best way to fetch this JSON data and display it in the list.
package com.example.ams;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class ViewClasses extends Activity {
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_classes);
new GetInfo().execute();
// ==============Functionality Start====================
// final ListView listview = (ListView) findViewById(R.id.listview);
}
private class GetInfo extends AsyncTask<Void, Void, String> {
protected String doInBackground(Void... params) {
// Fetch the JSON from the web and we pass it as a string to
// the ON POST EXECUTE method
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(
"file.php?get=XXX");
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e(this.toString(), "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}
protected void onPostExecute(String result) {
// Here it should turn it into a JSON and then display it in a list.
// Gets the list view
final ListView listview = (ListView) findViewById(R.id.listview);
// Converts the String to a JSON array
System.out.println(result);
JSONArray jsonArray;
try {
System.out.println(result);
jsonArray = new JSONArray(result);
Log.i(ViewClasses.class.getName(), "Number of entries "
+ jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Log.i(ViewClasses.class.getName(),
jsonObject.getString("text"));
// Converts JSON array to Java Array
final ArrayList<String> list = new ArrayList<String>();
// values instead of jsonArray
if (jsonArray != null) {
int len = jsonArray.length();
for (int i1 = 0; i1 < len; i1++) {
list.add(jsonArray.get(i).toString());
}
}
final StableArrayAdapter adapter = new StableArrayAdapter(
getApplicationContext(),
android.R.layout.simple_list_item_1, list);
listview.setAdapter(adapter);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class StableArrayAdapter extends ArrayAdapter<String> {
HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();
public StableArrayAdapter(Context context, int textViewResourceId,
List<String> objects) {
super(context, textViewResourceId, objects);
for (int i = 0; i < objects.size(); ++i) {
mIdMap.put(objects.get(i), i);
}
}
#Override
public long getItemId(int position) {
String item = getItem(position);
return mIdMap.get(item);
}
#Override
public boolean hasStableIds() {
return true;
}
}
}
My Layout XML file looks like this
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Running this code I am getting a blank screen.
Any help, pointers, hints would be greatly appreciated
It is just returning JSONArray with Strings, so you should not create JSONObject from it.
JSONObject jsonObject = jsonArray.getJSONObject(i);
this will cause Exception as JSONArray doesn't contain JSONObjects.
So parse like this
ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < jsonArray.length(); i++) {
list.add(jsonArray.get(i).toString());
}

Download images from remote URLs

Currently I am developing an Android app containing a list view which displays links for Youtube videos. The application gets its data from the server as JSON. Now I am trying to display thumbnails for these video from this subdomain - http://img.youtube.com/vi/.
But the images don't show up in the list view.
Here is the code for the project :
1 - canticlesActivity.java
package com.shadatv.shada;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class canticlesActivity extends ListActivity {
TextView httpStuff;
HttpClient client;
JSONArray canticles;
String picpath = "http://img.youtube.com/vi/";
File sdcard = Environment.getExternalStorageDirectory();
File shadaRoot = new File(sdcard.getAbsolutePath() + "/shada_Folder");
private static final String CA_NAME = "ca_name";
private static final String CA_LINK = "ca_link";
private static final String CA_IMG = "ca_img";
private static final String URL = "http://dt-works.com/ags/shadatv/canticles/android_data";
ArrayList<HashMap<String, String>> canticlesList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.canticles);
httpStuff = (TextView) findViewById(R.id.textView1);
client = new DefaultHttpClient();
new Read().execute();
}
public JSONArray allCanticles() throws ClientProtocolException, IOException, JSONException {
StringBuilder url = new StringBuilder(URL);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONArray canticles = new JSONArray(data);
return canticles;
} else {
Toast.makeText(getBaseContext(), "error", Toast.LENGTH_SHORT).show();
return null;
}
}
public void downloadImage(String fileURL) {
try {
// Toast.makeText(getBaseContext(), "baaad", Toast.LENGTH_SHORT).show();
String finlpth = "";
finlpth = picpath + fileURL + "/2.jpg";
shadaRoot.mkdirs();
URL u = new URL(finlpth);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
File DownloadedFile = new File(shadaRoot, fileURL + ".jpg");
// if(!outfile.exists())
FileOutputStream f = new FileOutputStream(DownloadedFile);
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
Log.d("Downloader", e.getMessage());
}
}
public class Read extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... params) {
canticlesList = new ArrayList<HashMap<String, String>>();
try {
canticles = allCanticles();
for (int i = 0; i < canticles.length(); i++) {
JSONObject canticle = canticles.getJSONObject(i);
String ca_name = canticle.getString(CA_NAME);
String ca_link = canticle.getString(CA_LINK);
downloadImage(ca_link);
HashMap<String, String> map = new HashMap<String, String>();
map.put(CA_NAME, ca_name);
map.put(CA_LINK, ca_link);
map.put(CA_IMG, ca_link + ".jpg");
canticlesList.add(map);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
ListAdapter adapter = new SimpleAdapter(canticlesActivity.this,
canticlesList,R.layout.list_item,
new String[] {CA_NAME, CA_LINK, CA_IMG},
new int[] {R.id.ca_name, R.id.ca_link, R.id.ca_img});
setListAdapter(adapter);
}
}
}
2 - list_item.xml
<?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:background="#drawable/list_selector"
android:orientation="horizontal" >
<!-- Product id (pid) - will be HIDDEN - used to pass to other activity -->
<ImageView
android:id="#+id/ca_img"
android:layout_width="50dip"
android:layout_height="50dip"
android:contentDescription="#string/desc"
/>
<TextView
android:id="#+id/ca_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<!-- Name Label -->
<TextView
android:id="#+id/ca_link"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:textSize="17sp"
android:textStyle="bold"
android:visibility="gone" />
</LinearLayout>
You can use UniversalImageLoader
it very simple for using -imageLoader.displayImage(imageUri, imageView);
Downloading images and then displaying in ListView is bad process. Because just think if you are having >100 images then it will take more time to display it.
And now optimization which i would suggest is: Implement logic for lazy loading of Images inside ListView.
Refer below examples:
Lazy List by Fedor
Universal Image Loader
ImageLoader by Novoda
In youtube JSON data ,The entire videos information will be in "entry" JSON array. You are creating same tag name for all the entires in the Hashmap.. If you give same tag for all entries then it will display last entry image. Please change the TAG NAME to "map.put(CA_IMG+i, ca_link + ".jpg");"
I hope this solution will be helpful for you.

How to get Spinning Progress Bar at starting of Application

i am new in android. I managed to parse JSON file to my application. Now i want to use AsyncTask to get Spinning progressBa untill application starts and load data. I tried to read many things, but they only give how to get progressbar on onclick events or for downloading events.
This is my code...
I just confused about how to start progressbar at starting of your application and which part of following code goes to which method of asycTask class....
package com.demojson;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.app.ListActivity;
public class MainActivity extends ListActivity {
private static String url = "http://timepasssms.com/webservices/ws.php?type=category";
private static final String TAG_DATA = "DATA";
private static final String TAG_0 = "0";
private static final String TAG_ID = "id";
private static final String TAG_1 = "1";
private static final String TAG_NAME = "name";
private static final String TAG_2 = "2";
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_3 = "3";
private static final String TAG_NEW_NAME = "new_name";
private static final String TAG_4 = "4";
private static final String TAG_STATUS = "status";
JSONArray jArray = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<HashMap<String, String>> contents = new ArrayList<HashMap<String, String>>();
JSONMethod metObj = new JSONMethod();
JSONObject jOb = metObj.getUrl(url);
try {
jArray = jOb.getJSONArray(TAG_DATA);
for (int i = 0; i < jArray.length(); i++) {
JSONObject child = jArray.getJSONObject(i);
String tag_0 = child.getString(TAG_0);
String id = child.getString(TAG_ID);
String tag_1 = child.getString(TAG_1);
String name = child.getString(TAG_NAME);
String tag_2 = child.getString(TAG_2);
String description = child.getString(TAG_DESCRIPTION);
String tag_3 = child.getString(TAG_3);
String new_name = child.getString(TAG_NEW_NAME);
String tag_4 = child.getString(TAG_4);
String status = child.getString(TAG_STATUS);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_NAME , name);
contents.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(this, contents,
R.layout.list_items, new String[] { TAG_NAME },
new int[] { R.id.tvName });
setListAdapter(adapter);
// --To get listview set...--
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String item = ((TextView)view.findViewById(R.id.tvName)).getText().toString();
Toast toast = Toast.makeText(getApplicationContext(), item , Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
});
}
}
and JSONMethod Class...
package com.demojson;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import android.util.Log;
public class JSONMethod {
InputStream is = null;
JSONObject jObj=null;
String json = "";
public JSONObject getUrl(String url){
try{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpRespone = httpClient.execute(httpPost);
HttpEntity httpEntity = httpRespone.getEntity();
is = httpEntity.getContent();
}catch(UnsupportedEncodingException ue){
}catch(ClientProtocolException ce){
}catch(IOException ie){
}
try{
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line=null;
while((line=br.readLine())!= null){
sb.append(line + "/n");
}
is.close();
json = sb.toString();
}catch(Exception e){
Log.e("JSONMethod", "Error converting result" + e.toString());
}
try{
jObj = new JSONObject(json);
}catch(Exception e){
Log.e("JSONMethod", "Error parsing data" + e.toString());
}
return jObj;
}
}
here is xml files...
activity_main.xml
<?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">
<!-- Main ListView
Always give id value as list(#android:id/list)
-->
<ImageView
android:id="#+id/imageView1"
android:layout_width="fill_parent"
android:layout_height="60dp"
android:src="#drawable/timepasssms" />
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_gravity="center"
android:layout_height="wrap_content"/>
</LinearLayout>
and list_item.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="match_parent"
android:background="#drawable/round_edge"
android:orientation="vertical" >
<TextView
android:id="#+id/tvName"
android:layout_width="fill_parent"
android:layout_height="45dp"
android:layout_marginLeft="10dp"
android:gravity="left"
android:padding="5dp"
android:textColor="#DF7401"
android:textSize="20dp" />
</LinearLayout>
here is example `
#Override
protected void onPostExecute(Object table) {
// TODO Auto-generated method stub
super.onPostExecute(table);
dialog.dismiss();
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog=ProgressDialog.show(Yourclass.this, "Loading Data.", "Please Wait");
}
`
I hope would be helpful
Try Using Async class and in doInBackground() method load your List view.
This is how to call Async Class
new LoadListView(this).execute(listView);
And here is your Async Class
public class LoadListView extends AsyncTask<ListView> {
private Context context;
public loadListView(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.show();
}
#Override
protected String doInBackground(String... aurl) {
//Here you need to load your ListView
return null;
}
protected void onProgressUpdate(String... progress) {
//Show progress bar here
}
#Override
protected void onPostExecute(String unused) {
//Hide Progress Bar Here
}
It will automatically hide progress bar when listview is loaded..

list view setChecked() selects multiple items instead of one

I have a listview which populates the data using CheckedTextView. Here is the xml
<?xml version="1.0" encoding="utf-8"?>
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textSize="14dp"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:paddingRight="5dp"
android:paddingLeft="5dp"
android:textColor="#color/blue"
android:checked="false"
android:id="#+id/listviewsubview_textview" >
</CheckedTextView>
On item click listener, show tick on the right of the item, but not only that item shows tick other multiple items also show tick. Wierd thing is all are ticks after same number of row. I dont know where I am doing wrong.
Here is the code
package com.chegg.android.account;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckedTextView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import com.chegg.android.R;
import com.chegg.android.api.RestClient;
import com.chegg.android.objects.StudentInfo;
import com.chegg.android.util.Util;
public class MajorActivity extends MainActivity {
public ListView majorsListView;
public String url;
public HashMap<String, String> majorMap = new HashMap<String, String>();
public JSONArray resultArray = new JSONArray();
public JSONObject resultObj = new JSONObject();
public ArrayList<String> majorNameArray = new ArrayList<String>();
public RestClient restClient = null;
public StudentInfo studentInfo = null;
public HashMap majors = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.majors);
Object campusObj = this.getIntent().getStringExtra("campus_id");
restClient = new RestClient();
if(campusObj!=null) {
String campusId = campusObj.toString();
url = "school/majors/"+campusId;
} else {
url = "school/majors";
}
String result = restClient.connect(url);
try {
JSONArray jsonArray = new JSONArray(result);
for(int i=0;i<jsonArray.length();i++) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
String name = jsonObj.getString("name");
majorMap.put(name,jsonObj.getString("id"));
majorNameArray.add(name);
}
} catch (JSONException e) {
e.printStackTrace();
}
majorsListView = (ListView)findViewById(R.id.majors_listview);
majorsListView.setChoiceMode(ListView.CHOICE_MODE_NONE);
majorsListView.setAdapter(new ArrayAdapter<String>(MajorActivity.this, R.layout.list_view_subview,majorNameArray));
studentInfo = (StudentInfo)this.getIntent().getSerializableExtra("studentInfo");
if(studentInfo.getMajors()!=null) {
majors = (HashMap)studentInfo.getMajors();
} else {
majors = new HashMap();
}
//majorsListView.setAdapter(new MajorsAdapter(MajorActivity.this, R.layout.list_view_subview,majorNameArray,majors));
majorsListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
CheckedTextView selectedView = (CheckedTextView)view;
Drawable chevron = getResources().getDrawable(R.drawable.chevron);
chevron.setBounds( 0, 0, chevron.getMinimumWidth(), chevron.getMinimumHeight() );
String text = selectedView.getText().toString();
if(!selectedView.isChecked()) {
selectedView.setChecked(true);
selectedView.setCheckMarkDrawable(R.drawable.chevron);
majors.put(text, majorMap.get(text));
} else {
selectedView.setChecked(false);
selectedView.setCheckMarkDrawable(null);
if(majors.containsKey(text)) {
majors.remove(text);
}
}
JSONObject jsonFinalResult = new JSONObject();
try {
Iterator it = majors.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
JSONObject jsonObj = new JSONObject();
System.out.println(pairs.getKey() + " = " + pairs.getValue());
jsonObj.put("name", pairs.getKey());
jsonObj.put("id",pairs.getValue());
resultArray.put(jsonObj);
}
jsonFinalResult.accumulate("majors", resultArray);
} catch (JSONException e) {
e.printStackTrace();
}
String url = "account?access_token="+ accessToken;
Log.i("json *****",jsonFinalResult.toString());
String result = restClient.connectHttpsPostPutJson(url, jsonFinalResult.toString(), "PUT");
Log.i("*******",result);
String checkError = Util.checkResponseForError(result);
if(checkError.equals("") || checkError == null) {
studentInfo = StudentInfo.getObjectFromJson(result);
cacheData(studentInfo, "studentInfo", "update");
} else {
alertbox.setMessage(checkError);
alertbox.setNeutralButton("ok", null);
alertbox.show();
}
}
});
}
}
Any help is appreciated
majorsListView.setChoiceMode(ListView.CHOICE_MODE_NONE);
That should be ListView.CHOICE_MODE_MULTIPLE, so Android will track your selections for you. Then, you can also get rid of your OnItemClickListener. When the user is done making selections, getCheckedItemPositions() will tell you which ones they chose, so you can update your data model.
Your current implementation ignores the effects of row recycling (one CheckedTextView widget will be used for any number of possible positions in your ArrayAdapter).

Categories

Resources