Android clickable listview - android

I have a android code which that get some data in json format from php file,
I successfully created a listview using those json now I want to create a second activity to show product details when I click on those items.
Here is the code :
public class MainActivity extends Activity {
private String jsonResult;
private String url = "xxxx/get_all_products.php";
private ListView listView;
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_PRICE = "price";
private static final String TAG_FOUND = "found";
private static final String TAG_DESCRIPTION = "description";
ArrayList<HashMap<String, String>> productList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView1);
productList = new ArrayList<HashMap<String, String>>();
accessWebService();
}
// 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>> productList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("products");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("name");
String price = jsonChildNode.optString("price");
String found = jsonChildNode.optString("found");
// String outPut = name + "-" + number;
// String outPut = name + "-" + price + "-" + found;
// productList.add(createProduct("products", outPut));
HashMap<String, String> product = new HashMap<String, String>();
product.put(TAG_NAME, name);
product.put(TAG_FOUND, found);
product.put(TAG_PRICE, price);
productList.add(product);
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
SimpleAdapter simpleAdapter = new SimpleAdapter(this, productList,
R.layout.list_item, new String[] { TAG_NAME, TAG_PRICE,
TAG_FOUND }, new int[] { R.id.name,
R.id.price, R.id.found });
listView.setAdapter(simpleAdapter);
}
}
and also there are there are two xml layout files.
I read many examples for doing this about setOnItemClickListener whit no success.....
for example tried this with no success :
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String selval = ((TextView) view).getText().toString();
Intent intnt = new Intent(getApplicationContext(), SingleListItem.class);
intnt.putExtra("selval ", selval);
}
Here are the errors :
FATAL EXCEPTION: main
java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.widget.TextView
at sig.example.com.sig00.MainActivity$1.onItemClick(MainActivity.java:59)
Here are xml files :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<!-- Name Label -->
<!-- android:id="#+id/listView1" -->
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="14dp">
</ListView>
and the list_item.xml is
<?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="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp" >
<!-- Name Label -->
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:paddingTop="6dip"
android:textColor="#43bd00"
android:textSize="16sp"
android:textStyle="bold"
android:gravity="center"/>
<!-- Email label -->
<TextView
android:id="#+id/price"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textColor="#acacac" />
<!-- Mobile number label -->
<TextView
android:id="#+id/found"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:textColor="#5d5d5d"
android:textStyle="bold" />
</LinearLayout>

Replace your code from your setOnItemClickListener() to this one :
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String selval = listview.getItemAtPosition(position).getText().toString();
// Also I've found a solution on SO that a guy solved this problem doing soemthing like this :
// TextView txt = (TextView) parent.getChildAt(position - listview.firstVisiblePosition()).findViewById(R.id.sometextview);
// String keyword = txt.getText().toString();
Intent intnt = new Intent(getApplicationContext(), SingleListItem.class);
intnt.putExtra("selval ", selval);
EDIT
Your error is that in your intent you are putting as extra "selval ", with an BLANK SPACE so if in your next activity you are doing this :
Class SingleListItem extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.productdetails);
TextView txtProduct = (TextView) findViewById(R.id.product_label);
Intent i = getIntent(); // getting attached intent data
String selval = i.getStringExtra("selval"); // displaying selected product name txtProduct.setText(selval);
}
It never will return your selval string cause you are asking for "sevlal" not from "selval ".
Just remove your unnecessary space and it will work :)

The View in onItemClick is not a TextView, it's the entire row. You should do the following
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//String selval = ((TextView) view.findViewById(R.id.yourId)).getText().toString();
HashMap<String, String> item = parent.getItemAtPosition(position);
String selval = item.get(TAG_PRICE);
Intent intnt = new Intent(getApplicationContext(), SingleListItem.class);
intnt.putExtra("selval ", selval);
}

Related

How to show all data according to particular item clicked in ListView to new Intent

I want to show, data read from mysql to setOnItemClickListener. Like whatsapp, i want that data read from database only show in one line with (...) after each line ends and after click on any listview item, all data will print in new intent having textview.
My java code from fetching to show data in listview.
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) {
try {
ListDrwaer();
pdialog.dismiss();
} catch (Exception e) {
pdialog.dismiss();
Toast.makeText(getApplicationContext(), "Error: Unreachable Database", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onPreExecute() {
pdialog = ProgressDialog.show(Home.this, "Loading Content", "Please Wait...", true);
super.onPreExecute();
}
}
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[]{url});
}
public void ListDrwaer() {
dataList = new ArrayList<>();
String str = "", str2 = "";
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("works");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = (jsonChildNode.getString("name"));
String username = jsonChildNode.getString("username");
String password = jsonChildNode.getString("password");
String details = jsonChildNode.getString("details");
String outPut = "\n\nName: " + name + "\n\n" + "Username: " + username + "\n\n" + "Password: " + password + "\n\n" + "Details: " + details + "\n\n";
dataList.add(createList("details", outPut));
}
Collections.reverse(dataList);
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
simpleAdapter = new SimpleAdapter(this, dataList,
android.R.layout.simple_list_item_1,
new String[]{"details"}, new int[]{android.R.id.text1});
listView.setAdapter(simpleAdapter);
}
private HashMap<String, String> createList(String key, String value) {
HashMap<String, String> data = new HashMap<>();
data.put(key, value);
return data;
}
Here is layout file where i show all data in listview.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.mr_robot.app_proj.Home"
tools:showIn="#layout/activity_home">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView2"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="62dp" />
</RelativeLayout>
Here is layout file of new intent where i wanna show all data after particular item clicked.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.mr_robot.temp_proj.Show"
android:background="#ffffff">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="false">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/list_tag"
android:layout_alignParentTop="true"
android:textColor="#000000"
android:layout_centerHorizontal="true"
android:layout_marginTop="44dp" />
</ScrollView>
</RelativeLayout>
you can use 2 datalist, one contains the real data, and one contain some part of text (using substring and add (...)). you can display using the second one, but when it's clicked then u send the data from the real list
ListView lv = (ListView) findViewById(R.id.listview2);
lv.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3)
{
String value = (String)adapter.getItemAtPosition(position);
// assuming string and if you want to get the value on click of list item
// your code using intent
Intent intent = new Intent(FirstActivity.this, ShownActivity.class);
// put your real data here
intent.putExtra("keydata", datalist2[position]);
startActivity(intent);
}
});
and then you can use String data = getIntent.getExtra("keydata"); in the next activity and show your data

ListView not showing JSON data

My listview is suposed to import json data into the listview, but it doesnt.
Here is my rooster.xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.nijdeken.ccapp.rooster">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Les"
android:id="#+id/lesson"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Lokaal"
android:id="#+id/room"
android:layout_above="#android:id/list"
android:layout_toLeftOf="#+id/teacher"
android:layout_toStartOf="#+id/teacher"
android:layout_marginRight="57dp"
android:layout_marginEnd="57dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Docent"
android:id="#+id/teacher"
android:layout_above="#android:id/list"
android:layout_toLeftOf="#+id/start"
android:layout_toStartOf="#+id/start"
android:layout_marginRight="92dp"
android:layout_marginEnd="92dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Tijd"
android:id="#+id/start"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-thin"
android:id="#android:id/list"
android:layout_below="#+id/lesson"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
And my Rooster.java file:
public class rooster extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://api.ccapp.it/v2/zportal/schedule/37?token=df679ovlka5urmajmd7tg28lc0";
String apiUrl = "http://api.ccapp.it";
// JSON Node names
private static final String TAG_TIME = "start";
private static final String TAG_ROOM = "locations";
private static final String TAG_TEACHER = "teachers";
private static final String TAG_LESSON = "subjects";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rooste);
// ListView listView = (ListView) findViewById(android.R.id.list);
// FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
// fab.attachToListView(listView);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.lesson))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.room))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.teacher))
.getText().toString();
// Starting single contact activity
// Intent in = new Intent(getApplicationContext(),
// SingleContactActivity.class);
// in.putExtra(TAG_NAME, name);
// in.putExtra(TAG_EMAIL, cost);
// in.putExtra(TAG_PHONE_MOBILE, description);
// startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
Servicehandler sh = new Servicehandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, Servicehandler.GET);
Log.d("Schedule: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray("");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String subject = c.getString(TAG_LESSON);
String teachers = c.getString(TAG_TEACHER);
String location = c.getString(TAG_ROOM);
String start = c.getString(TAG_TIME);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_LESSON, subject);
contact.put(TAG_TEACHER, teachers);
contact.put(TAG_ROOM, location);
contact.put(TAG_TIME, start);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
rooster.this, contactList,
R.layout.list_item, new String[] { TAG_LESSON, TAG_ROOM,
TAG_TEACHER, TAG_TIME }, new int[] { R.id.lesson,
R.id.room, R.id.teacher, R.id.time });
setListAdapter(adapter);
}
}
public static void getRooster(String appcode, int week){
// url="http://api.ccapp.it/v2/zportal/schedule/"+week+"?token="+appcode;
url="http://nijdeken.com/json/schedule.json";
}
}
Your JSON url is giving null output. I tried in browser then i got the value as empty []....
Please give the input to your JSON.
http://api.ccapp.it/v2/zportal/schedule/37?token=df679ovlka5urmajmd7tg28lc0

How to set image like background in listview if image is must be loaded from url which parsed from JSON?

I've got a program which parses JSON file from server and makes a listview of it's objects. I need to create background image (or even a thumbnail near title) for each element of list and this image must be downloaded from url.
private static String url = "my url here";
private static final String TAG_NAME = "name";
private static final String TAG_AUTHOR = "author";
private static final String TAG_POSTS = "posts";
private static final String TAG_ID = "id";
private static final String TAG_TITLE = "title";
private static final String TAG_DATE = "date";
private static final String TAG_CONTENT = "content";
private static final String TAG_THUMBNAIL_URL = "thumbnail";
JSONArray posts = null;
ArrayList<HashMap<String, String>> postList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
postList = new ArrayList<HashMap<String,String>>();
ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String c_id = ((TextView)view.findViewById(R.id.id)).getText().toString();
String c_title = ((TextView)view.findViewById(R.id.title)).getText().toString();
String c_date = ((TextView)view.findViewById(R.id.date)).getText().toString();
String c_content = ((TextView)view.findViewById(R.id.content)).getText().toString();
String a_name = ((TextView)view.findViewById(R.id.name)).getText().toString();
ImageView image = (ImageView) findViewById(R.id.thumb);
Intent in = new Intent(getApplicationContext(), SimplePostActivity.class);
in.putExtra(TAG_AUTHOR, a_name);
in.putExtra(TAG_ID, c_id);
in.putExtra(TAG_TITLE, c_title);
in.putExtra(TAG_DATE, c_date);
in.putExtra(TAG_CONTENT, c_content);
startActivity(in);
Bitmap bMap = BitmapFactory.decodeFile("/sdcard/" + c_id + ".jpeg");
image.setImageBitmap(bMap);
}
});
new GetData().execute();
}
public class GetData extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
Parser parser = new Parser();
String jsonStr = parser.makeServiceCall(url, Parser.GET);
Log.d("Response: ", "> " +jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
posts = jsonObj.getJSONArray(TAG_POSTS);
for (int i = 0; i < posts.length(); i++) {
JSONObject num = posts.getJSONObject(i);
String id = num.getString(TAG_ID);
String title = num.getString(TAG_TITLE);
String date = num.getString(TAG_DATE);
String content = num.getString(TAG_CONTENT);
JSONObject author_object = num.getJSONObject(TAG_AUTHOR);
String name = author_object.getString(TAG_NAME);
HashMap<String, String> post = new HashMap<String, String>();
post.put(TAG_NAME, name);
post.put(TAG_ID, id);
post.put(TAG_TITLE, title);
post.put(TAG_DATE, date);
post.put(TAG_CONTENT, content);
postList.add(post);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("Parser", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if(pDialog.isShowing())
pDialog.dismiss();
ListAdapter adapter = new SimpleAdapter(MainActivity.this, postList, R.layout.list_item,
new String[] {TAG_NAME, TAG_ID, TAG_DATE, TAG_TITLE, TAG_CONTENT},
new int[] {R.id.name, R.id.id, R.id.title, R.id.date, R.id.content});
setListAdapter(adapter);
}
}
Can somebody tell me how to do that ? I don't even know how to start...
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<TextView
android:id="#+id/title"
android:textColor="#0fffff"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone"/>
<TextView
android:id="#+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone" />
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/></RelativeLayout>
You must:
Add an ImageView to your layout.
In order to display images you'll have to implement your own listview adapter and invoke images loading in getView method.
Use Picasso library to background download. It's use is as simple as:
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);

setOnClickListener not responding

I found my answer in my recent post but now something is gaining focus of my listview so I when I try to click on a which list item I want to select nothing happens. I had did some research and learned that something takes focus of the activity when this happens and the only thing I can think of that is causing this is my scollview. I have tried putting android:focusable="false"> in my xml file under my scrollview but I still get the same results. So I'm just hoping somebody can give me some advice
ListActivity:
public class List extends ListActivity {
ArrayList<HashMap<String, String>> questionList;
final String TAG_RESULTS = "results";
static final String TAG_QUESTION_SUBJECT = "Subject";
final String TAG_QUESTION_NUMANSWERS = "NumAnswers";
final String TAG_QUESTION = "question";
final String TAG_QUESTION_CONTENT = "Content";
final String TAG_QUESTION_CHOSENANSWER = "ChosenAnswer";
final String TAG_ANSWERS = "Answers";
final String TAG_ANSWER = "Answer";
final String TAG_ANSWERS_CONTENT = "content";
final String TAG_QUERY = "query";
JSONArray question = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.listview);
questionList = new ArrayList<HashMap<String, String>>();
new LoadAllData().execute();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 100) {
Intent intent = getIntent();
startActivity(intent);
finish();
}
}
class LoadAllData extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
ProgressDialog pDialog;
pDialog = new ProgressDialog(ListView.this);
pDialog.setMessage("Loading Data. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
if (pDialog != null && pDialog.isShowing()) pDialog.dismiss();
}
protected String doInBackground(String... args) {
try {
Intent in = getIntent();
String searchTerm = in.getStringExtra("TAG_SEARCH");
String query = URLEncoder.encode(searchTerm, "utf-8");
String URL = "http://answers.yahooapis.com/AnswersService/V1/questionSearch?appid=4vCW8F3V34GzdMlXOS.yc2WfF5DCnCgqhK0nwCJmEFDgRwEbIgnAoEgJ0zynqOAWtQ&query="+ query +"&search_in=question&sort=relevance&results=25&output=json";
JSONParsser jParser = new JSONParsser();
JSONObject json = jParser.readJSONFeed(URL);
try {
//question = json.getJSONArray(TAG_QUESTION);
JSONArray questions = json.getJSONObject("all").getJSONArray("questions");
for(int i = 0; i < questions.length(); i++) {
JSONObject question = questions.getJSONObject(i);
String Subject = question.getString(TAG_QUESTION_SUBJECT);
String NumAnswers = question.getString(TAG_QUESTION_NUMANSWERS);
String ChosenAnswer = question.getString(TAG_QUESTION_CHOSENANSWER);
String Content = question.getString(TAG_QUESTION_CONTENT);
//JSONArray Answers = question.getJSONObject(TAG_ANSWERS).getJSONArray(TAG_ANSWER);
//JSONObject Answer = Answers.getJSONObject(0);
//String Content = Answer.getString(TAG_ANSWERS_CONTENT);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_QUESTION_SUBJECT, Subject);
map.put(TAG_QUESTION_NUMANSWERS, NumAnswers);
questionList.add(map);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return TAG_QUESTION ;
}
protected void onPostExecute(String file_URL) {
ListAdapter adapter = new SimpleAdapter(getBaseContext(), questionList,
R.layout.listview,
new String[] { TAG_QUESTION_SUBJECT, TAG_QUESTION_NUMANSWERS }, new int[] {
R.id.Subject, R.id.NumAnswers });
setListAdapter(adapter);
android.widget.ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String Subject = ((TextView) findViewById(R.id.Subject)).getText().toString();
String Content = ((TextView) findViewById(R.id.Content)).getText().toString();
String ChosenAnswer = ((TextView) findViewById(R.id.ChosenAnswer)).getText().toString();
Intent i = new Intent(ListView.this, SingleListItem.class);
i.putExtra("TAG_QUESTION_SUBJECT", Subject);
i.putExtra("TAG_QUESTION_CONTENT", Content);
i.putExtra("TAG_QUESTION_CHOSENANSWER", ChosenAnswer);
startActivity(i);
}
});
}}
}
list.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:orientation="vertical" >
<TextView
android:id="#+id/Subject"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/NumAnswers"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/ChosenAnswer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/Content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="false">
</ScrollView>
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
Try moving your listener outside of the AsyncTask. Make it a member variable and initialize it in onCreate()
public class List extends ListActivity {
ListView lv;
ArrayList<HashMap<String, String>> questionList;
...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.listview);
questionList = new ArrayList<HashMap<String, String>>();
lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String Subject = ((TextView) findViewById(R.id.Subject)).getText().toString();
String Content = ((TextView) findViewById(R.id.Content)).getText().toString();
String ChosenAnswer = ((TextView) findViewById(R.id.ChosenAnswer)).getText().toString();
Intent i = new Intent(ListView.this, SingleListItem.class);
i.putExtra("TAG_QUESTION_SUBJECT", Subject);
i.putExtra("TAG_QUESTION_CONTENT", Content);
i.putExtra("TAG_QUESTION_CHOSENANSWER", ChosenAnswer);
startActivity(i);
}
});
new LoadAllData().execute();
Your AscncTask is finishing so your listener is probably not around anymore. You can still set your Adapter there just move the onItemClick() and the initialization.
Edit
Since its ListActivity you don't need to set the listener on it. Just implement the method
public void onListItemClick(ListView l, View v, int position, long id)
{
// do your work
}

Can not populate listview from async task

I have an activity in which I have to populate a listview. The activity posts to an url and receives a JSON in response. I have parsed the JSON to display in a listview, but the listview is not getting populated.
The complete code for the activity:
public class RegisterFirstActivity extends ListActivity {
private static final String TAG_CODE = "Code";
private static final String TAG_ID = "Id";
private static final String TAG_LAT = "Lat";
private static final String TAG_LON = "Lon";
private static final String TAG_NAME = "Name";
static String response_str=null;
static String response_code=null;
String ac_code;
String ac_id;
String ac_lat;
String ac_lon;
String ac_name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register_first);
sendPostRequest();
}
//sending async post request---------------------------------------------------------------------------------------
private void sendPostRequest() {
class SendPostReqAsyncTask extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
String result = "";
HttpClient hc = new DefaultHttpClient();
String message;
//HttpPost p = new HttpPost("http://192.168.1.60/tr/MobileService/GetAC");
HttpPost p = new HttpPost("http://bumba27.byethost16.com/xxxxxxx/");
JSONObject object = new JSONObject();
try {
//object.put("Id",deviceid);
//object.put("StringValue",value);
// object.put("last_name", lastname);
// object.put("first_name", firstname);
// object.put("email", email);
} catch (Exception ex) {
}
try {
message = object.toString();
p.setEntity(new StringEntity(message, "UTF8"));
p.setHeader("Content-type", "application/json");
HttpResponse resp = hc.execute(p);
response_code=""+ resp.getStatusLine().getStatusCode();
Log.d("Response Code: ", "" + response_code);
InputStream inputStream = resp.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
response_str= stringBuilder.toString();
parse_json_str(response_str);
if (resp != null) {
if (resp.getStatusLine().getStatusCode() == 204)
result = "true";
makeAToast("Response: "+resp.toString());
}
Log.d("Status line", "" + resp.getStatusLine().getStatusCode());
} catch (Exception e) {
e.printStackTrace();
Log.i("Error in response: ",e.getMessage());
}
return result;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
//writeToFile(result, "record.txt");
Log.i("RESPONSE",result);
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute();
}
//-----------------------------------------------------------------------------------------------
public void parse_json_str(String json_str)
{
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
JSONArray lJSONArray;
String jString = json_str;
try
{
lJSONArray = new JSONArray( jString );
JSONObject lJSONObject;
for ( int i = 0; i < lJSONArray.length(); i++ )
{
lJSONObject = lJSONArray.getJSONObject( i );
// PARSE FIELD HERE
ac_code = lJSONObject.getString( TAG_CODE );
Log.i("Code: ",ac_code);
ac_id=lJSONObject.getString( TAG_ID );
Log.i("Id: ",ac_id);
ac_lat=lJSONObject.getString( TAG_LAT );
Log.i("Lat: ",ac_lat);
ac_lon=lJSONObject.getString( TAG_LON );
Log.i("Lon: ",ac_lon);
ac_name=lJSONObject.getString( TAG_NAME );
Log.i("Name: ",ac_name);
// ETC
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_CODE, ac_code);
map.put(TAG_ID, ac_id);
map.put(TAG_LAT, ac_lat);
map.put(TAG_LON, ac_lon);
map.put(TAG_NAME, ac_name);
Log.d("map","haeflloter putting");
Log.d("map",map+"");
// adding HashList to ArrayList
contactList.add(map);
//Log.d("tag name", contactList+"");
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, contactList,R.layout.list_item,new String[] { TAG_NAME }, new int[] {R.id.name});
Log.d("tag name", contactList+"");
setListAdapter(adapter);
}
catch( Exception e )
{
Log.d("catch", e+"");
}
}
public void makeAToast(String str) {
//yet to implement
Toast toast = Toast.makeText(this,str, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
The layout file activity_register_first :
<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)
-->
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
The 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:orientation="horizontal">
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- Name Label -->
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#43bd00"
android:textSize="16sp"
android:textStyle="bold"
android:paddingTop="6dip"
android:paddingBottom="2dip" />
<!-- Description label -->
</LinearLayout>
</LinearLayout>
The error which I am getting is:
02-15 19:26:46.154: D/catch(1429): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
I have followed this tutorial for listview.
Where am I going wrong? How to solve the issue?
In an AsyncTask, only onPreExecute(), onProgressUpdate() and onPostExecute() are executed in the UI Thread.
doInBackground() is executed in a background Thread.
You should store your data from doInBackground(), then update your UI in onPostExecute().
Edit:
Make your contactList a member of your AsyncTask, and add this code (not tested):
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(mContactList != null) {
ListAdapter adapter = new SimpleAdapter(this, contactList,R.layout.list_item,new String[] { TAG_NAME }, new int[] {R.id.name});
Log.d("tag name", contactList+"");
setListAdapter(adapter);
}
Log.i("RESPONSE",result);
}
UI changes have to be done in the UI thread. that is what onPostExecute() is for, that runs in the UI thread.

Categories

Resources