Data not being passed from listview into activity - android

I have finally got my onListItemClick to work but now it seems as if the data I have set to be passed into the next activity does not go through but the activity still starts. My application doesn't crash or anything it just loads the activity but the data I had set to go with it doesn't seem to be there. I have tried removing the scrollview but the data still doesn't seem to go through.
public class ListView extends ListActivity {
ArrayList<HashMap<String, String>> questionList;
final String TAG_RESULTS = "results";
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;
android.widget.ListView lv;
#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 onListItemClick(android.widget.ListView l, View v, int pos, long id) {
super.onListItemClick(l, v, pos, id);
String Subject = ((TextView) v.findViewById(R.id.Subject)).getText().toString();
String Content = ((TextView) v.findViewById(R.id.Content)).getText().toString();
String ChosenAnswer = ((TextView) v.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);
}
class LoadAllData extends AsyncTask<String, String, String> {
private Dialog pDialog;
#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://example.com";
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);
map.put(TAG_QUESTION_CONTENT, Content);
map.put(TAG_QUESTION_CHOSENANSWER, ChosenAnswer);
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 ;
}
#Override
protected void onPostExecute(String file_URL) {
ListAdapter adapter = new SimpleAdapter(getBaseContext(), questionList,
R.layout.listelements,
new String[] { TAG_QUESTION_SUBJECT, TAG_QUESTION_NUMANSWERS }, new int[] {
R.id.Subject, R.id.NumAnswers });
setListAdapter(adapter);
}}}
SingleListItem Activity:
public class SingleListItem extends Activity {
TextView title;
TextView question;
TextView bestanswer;
TextView subject;
TextView content;
TextView chosenanswer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.singlelistitem);
title = (TextView) findViewById(R.id.Title1);
question = (TextView) findViewById(R.id.Question1);
bestanswer = (TextView) findViewById(R.id.BestAnswer1);
subject = (TextView) findViewById(R.id.Subject1);
content = (TextView) findViewById(R.id.Content1);
chosenanswer = (TextView) findViewById(R.id.ChosenAnswer1);
Intent i = getIntent();
String Subject = i.getStringExtra("TAG_QUESTION_SUBJECT");
String Content = i.getStringExtra("TAG_QUESTION_CONTENT");
String ChosenAnswer = i.getStringExtra("TAG_QUESTION_CHOSENANSWER");
subject.setText(Subject);
content.setText(Content);
chosenanswer.setText(ChosenAnswer);
}
}
singlelistitem.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/Title1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Title:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/Subject1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.00"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/Question1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Question:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/Content1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.01"
android:textAppearance="?android:attr/textAppearanceSmall" />
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ScrollView>
<TextView
android:id="#+id/BestAnswer1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Best Answer:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/ChosenAnswer1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.01"
android:textAppearance="?android:attr/textAppearanceSmall" />
</LinearLayout>

Your keys are not the same.
You have this
i.putExtra(TAG_QUESTION_SUBJECT, Subject);
and TAG_QUESTION_SUBJECT is "Subject"
final String TAG_QUESTION_SUBJECT = "Subject";
Your get part is
String Subject = i.getStringExtra("TAG_QUESTION_SUBJECT"); // keys do not match
// must be "Subject"
Change it to below. Keys must match
String Subject = i.getStringExtra("Subject");
String Content = i.getStringExtra("Content");
String ChosenAnswer = i.getStringExtra("ChosenAnswer");

You should use the same keys for both sending and receiving. Some of the keys in your sending activity doesn't match with the keys in receiving activity.
For Sending:
map.put("Question", Subject);
map.put("NumAnswer", NumAnswers);
map.put("content", Content);
map.put("chosenAnswer", ChosenAnswer);
For Receiving:
String Subject = question.getString("Question");
String NumAnswers = question.getString("NumAnswer");
String ChosenAnswer = question.getString("chosenAnswer");
String Content = question.getString("content");

It looks like you've named the extras, e.g., "Subject" in your listview activity, then reference them differently in the single item activity:
String Subject = i.getStringExtra("TAG_QUESTION_SUBJECT");
Might look into that.

Related

How to pass parsed data from JSON through Intent?

I have created an android app with json parser (tutorial which I followed) and successfully displayed my data. However I cannot display more data in SingleActivity then I have in ListView. (Acctualy I can. But it's just the desired string names.) How can I do that?
SingleFilmActivity.java
public class SingleFilmActivity extends AppCompatActivity {
// JSON Node names
private static final String TAG_NAME = "jmeno";
private static final String TAG_START = "zacatek";
private static final String TAG_END = "konec";
private static final String TAG_CATEGORY = "kategorie";
private static final String TAG_POPIS = "popis";
private static final String TAG_BAN = "omezeni";
private static final String TAG_DAY = "den";
private static final String TAG_CLASS = "trida";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_film);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
String name = in.getStringExtra(TAG_NAME);
String zacatek = in.getStringExtra(TAG_START);
String konec = in.getStringExtra(TAG_END);
String kategorie = in.getStringExtra(TAG_CATEGORY);
String popis = in.getStringExtra(TAG_POPIS);
String omezeni = in.getStringExtra(TAG_BAN);
String den = in.getStringExtra(TAG_DAY);
String trida = in.getStringExtra(TAG_CLASS);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblZacatek = (TextView) findViewById(R.id.zacatek_label);
TextView lblKonec = (TextView) findViewById(R.id.konec_label);
TextView lblKategorie = (TextView) findViewById(R.id.kategorie_label);
TextView lblPopis = (TextView) findViewById(R.id.popis_label);
TextView lblOmezeni = (TextView) findViewById(R.id.omezeni_label);
TextView lblDen = (TextView) findViewById(R.id.den_label);
TextView lblTrida = (TextView) findViewById(R.id.trida_label);
lblName.setText(name);
lblZacatek.setText(zacatek);
lblKonec.setText(konec);
lblKategorie.setText(kategorie);
lblPopis.setText(popis);
lblOmezeni.setText(omezeni);
lblDen.setText(den);
lblTrida.setText(trida);
assert getSupportActionBar() != null;
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
Den2Fragment.java
public class Den2Fragment extends ListFragment {
private ProgressDialog pDialog;
// JSON Node names
private static final String TAG_FILMY = "filmy";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "jmeno";
private static final String TAG_START = "zacatek";
private static final String TAG_END = "konec";
private static final String TAG_CATEGORY = "kategorie";
private static final String TAG_POPIS = "popis";
private static final String TAG_BAN = "omezeni";
private static final String TAG_DAY = "den";
private static final String TAG_CLASS = "trida";
// Hashmap for ListView
private ArrayList<HashMap<String, String>> filmList = new ArrayList<>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_den2, container, false);
}
#Override
public void onViewCreated (View view, Bundle savedInstanceState) {
ListView lv = getListView();
// ListView on item click listener
lv.setOnItemClickListener(new AdapterView.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.name)).getText().toString();
String zacatek = ((TextView) view.findViewById(R.id.zacatek)).getText().toString();
String kategorie = ((TextView) view.findViewById(R.id.kategorie)).getText().toString();
Intent in = new Intent(getActivity().getApplicationContext(), SingleFilmActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_START, zacatek);
in.putExtra(TAG_END,TAG_END);
in.putExtra(TAG_CATEGORY, kategorie);
in.putExtra(TAG_POPIS, TAG_POPIS);
in.putExtra(TAG_BAN, TAG_BAN);
in.putExtra(TAG_DAY, TAG_DAY);
in.putExtra(TAG_CLASS, TAG_CLASS);
startActivity(in);
}
});
// Calling async task to get json
new GetFilmy().execute();
}
/** Async task class to get json by making HTTP call */
private class GetFilmy extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Prosím čekejte");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String url =" foo.com";
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray filmy = jsonObj.getJSONArray(TAG_FILMY);
// looping through All Films
for (int i = 0; i < filmy.length(); i++) {
JSONObject f = filmy.getJSONObject(i);
String id = f.getString(TAG_ID);
String name = f.getString(TAG_NAME);
String zacatek = f.getString(TAG_START);
String kategorie = f.getString(TAG_CATEGORY);
// tmp hashmap for single film
HashMap<String, String> film = new HashMap<>();
// adding each child node to HashMap key => value
film.put(TAG_ID, id);
film.put(TAG_NAME, name);
film.put(TAG_START, zacatek);
film.put(TAG_CATEGORY, kategorie);
// adding film to film list
filmList.add(film);
}
} 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);
// Dismiss the progress dialog
if (pDialog.isShowing()) pDialog.dismiss();
/** Updating parsed JSON data into ListView */
ListAdapter adapter = new SimpleAdapter(
getActivity(), filmList, R.layout.list_item_true,
new String[] { TAG_NAME, TAG_START, TAG_CATEGORY },
new int[] { R.id.name, R.id.zacatek, R.id.kategorie });
setListAdapter(adapter);
}
}
}
list_item_true.xml
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2sp"
android:paddingTop="6sp"
android:textColor="#000000"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="#+id/zacatek"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2sp"
android:textColor="#5d5d5d"
android:textStyle="bold" />
<TextView
android:id="#+id/kategorie"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="start"
android:textColor="#5d5d5d" />
content_single_film.xml
<TextView android:id="#+id/name_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="25sp"
android:textStyle="bold"
android:paddingTop="10sp"
android:paddingBottom="10sp"
android:textColor="#000000" />
<TextView android:id="#+id/zacatek_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#727272"
android:textStyle="bold" />
<TextView android:id="#+id/konec_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#727272" />
<TextView android:id="#+id/kategorie_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#727272"
android:textStyle="bold" />
<TextView android:id="#+id/omezeni_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#727272"
android:textStyle="bold" />
<TextView android:id="#+id/den_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#727272" />
<TextView android:id="#+id/trida_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#727272" />
<TextView android:id="#+id/popis_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#212121" />
Sorry for posting a lot of code, but I'm not sure what I am doing wrong.
Better you convert whole json to the string.
Intent intent= new Intent(Current.this, Next.class);
intent.putExtra("jsonValue",YourJson.toString);
startActivity(intent);
And in next activity you can get the value of the string with
Intent get=getIntent();
String json= get.getStringExtra("jsonValue");
you got your json String now you can parse it and get values
Better to use Gson. It is so simple and easy
Film film = new Film(...);
String gsonStr = new Gson().toJson(film);
Intent intent= new Intent(Current.this, Next.class);
intent.putExtra("gson",gsonStr);
startActivity(intent);
//From Next Activity
Intent intent=getIntent();
String gStr = intent.getStringExtra("gson");
Film getFilm = new Gson().fromJson(gStr,Film.class);

Android clickable listview

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);
}

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
}

Extra set of eyes needed with onItemClickListener

I have done everything that I could possibly do to figure out what is wrong with my onItemClickListener. There was one helpful person who tried to help but he or she said that they absolutely don't see anything wrong and that they do not understand why it is not working. I have done a lot reseach and looking other people codes trying to relate the issues but it still doesn't work. I really need a lot of set of eyes to assist me through this problem.
List Activity:
public class ListView extends ListActivity {
ArrayList<HashMap<String, String>> questionList;
final String TAG_RESULTS = "results";
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;
android.widget.ListView lv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.listview);
questionList = new ArrayList<HashMap<String, String>>();
new LoadAllData().execute();
}
class LoadAllData extends AsyncTask<String, String, String> {
private Dialog pDialog;
#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://example.com";
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 ;
}
#Override
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);
}
}
#Override
protected void onListItemClick(android.widget.ListView l, View v, int pos, long id) {
super.onListItemClick(l, v, pos, id);
String Subject = ((TextView) v.findViewById(R.id.Subject)).getText().toString();
String Content = ((TextView) v.findViewById(R.id.Content)).getText().toString();
String ChosenAnswer = ((TextView) v.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);
}
}
Issue is that my onItemClickListener is not being called similar to every other problem.
listview.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" >
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="afterDescendants" >
</ListView>
<TextView
android:id="#+id/Subject"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="false"
android:focusableInTouchMode="false" />
<TextView
android:id="#+id/NumAnswers"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="false"
android:focusableInTouchMode="false" />
<TextView
android:id="#+id/ChosenAnswer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="false"
android:focusableInTouchMode="false" />
<TextView
android:id="#+id/Content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="false"
android:focusableInTouchMode="false" />
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ScrollView>
</LinearLayout>
The ListActivity class comes with a protected method onListItemClick, override that with your handler code and do not call setOnItemClickListener directly. The ListActivity takes care of all initialization.
When using your layout: Your ListView has a wrong id. In XML, use the id
android:id="#android:id/list"
From the ListActivity reference:
[...] setting your own view layout with setContentView() in
onCreate(). To do this, your own view MUST contain a ListView object
with the id "#android:id/list" (or android.R.id.list if it's in code)

Categories

Resources