Json data in Listview - android

I am new to android. I got stuck on this point. I just want to get data of listview onclick event to another page by position. here is my code.
I got project contains error in the following line
i.putExtra("testonAray",listContents[position].toString());
Entire code below:
package com.example.listviewdemo;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.listviewdemo.CustomHttpClient;
public class MainActivity extends ListActivity {
TextView txt;
String returnString;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String name="sandeep";
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
// define the parameter
postParameters.add(new BasicNameValuePair("email",
name.toString()));
String response = null;
// call executeHttpPost method passing necessary parameters
try {
response = CustomHttpClient.executeHttpPost(
"http://indiaontaxi.com/android/myaccount.php", // your ip address if using localhost server
//"http://omega.uta.edu/~kmr2464/jsonscript.php", // in case of a remote server
postParameters);
// store the result returned by PHP script that runs MySQL query
String result = response.toString();
//parse json data
try {
JSONArray jArray = new JSONArray(result);
int jArrayLength = jArray.length();
final ArrayList<String> listContents = new ArrayList<String>(jArrayLength);
for(int i =0; i<jArray.length(); i++){
JSONObject json_data = jArray.getJSONObject(i);
listContents.add(json_data.getString("source"));
}
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, listContents));
txt = (TextView) findViewById(R.id.txt);
//myListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, ));
}catch(JSONException e){
Log.e("log_tag","Error parsin data "+e.toString());
}
}
catch (Exception e) {
Log.e("log_tag","Error in http connection!!" + e.toString());
}
/* setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, items));
txt = (TextView) findViewById(R.id.txt);
*/
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
// txt.setText(items[position]);
// Try to send the items[position] in the intent
Intent i = new Intent(this, SecondActivity.class);
i.putExtra("testonAray",listContents[position].toString());
startActivity(i);
}
#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;
}
}

// Try this code
i.putExtra("testonAray",listContents[position].toString());
// Replace the line
i.putExtra("testonAray",listContents.get(position).toString());

In Android 3.0 and above you need to do all network based actions separate from the UI thread.That is in a Async class. HEre is a similar post I made a few days ago; have a look at how you can make Async calls to JSON that are in a URL Trouble with JSON exception - Android

Change the code
Intent i = new Intent(this, SecondActivity.class);
i.putExtra("testonAray",listContents[position].toString());
to
Intent i = new Intent(MainActivity.this, SecondActivity.class);
i.putExtra("testonAray",listContents[position].toString());

Related

How to reuse data from a JSONArray which got data in onPostExecute

this is my code for getting data from a PHP site into a ListView.
package be.pressd.arrangementen;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener{
Button fetch;
EditText et;
String aantalPersonen;
private ListView lv;
private ArrayAdapter<String> listAdapter ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fetch = (Button) findViewById(R.id.fetchButton);
et = (EditText) findViewById(R.id.aantalPersonen);
// Find the ListView resource.
lv = (ListView) findViewById(R.id.arrangementenLijst);
listAdapter = new ArrayAdapter<String>(this, R.layout.line_row);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Toast.makeText(getApplicationContext(), "Click nummer " + position, Toast.LENGTH_LONG).show();
String arrangement = (String) lv.getItemAtPosition(position);
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(), ArrangementItem.class);
// sending data to new activity
i.putExtra("arrangement", arrangement);
startActivity(i);
}
});
fetch.setOnClickListener(this);
}
class task extends AsyncTask<String, String, Void>
{
private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
InputStream is = null ;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Fetching data...");
progressDialog.show();
progressDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface arg0) {
task.this.cancel(true);
}
});
}
#Override
protected Void doInBackground(String... params) {
String url_select = "http://mywebsite/thephpform.php?aantpers=" + aantalPersonen;
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try
{
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
//read content
is = httpEntity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection "+e.toString());
}
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = "";
while((line=br.readLine())!=null)
{
sb.append(line+"\n");
}
is.close();
result=sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result "+e.toString());
}
return null;
}
protected void onPostExecute(Void v) {
try
{ listAdapter.clear();
JSONArray Jarray = new JSONArray(result);
for(int i=0; i < Jarray.length(); i++)
{
JSONObject Jasonobject = null;
Jasonobject = Jarray.getJSONObject(i);
String name = Jasonobject.getString("naam");
listAdapter.add(name);
}
this.progressDialog.dismiss();
lv.setAdapter( listAdapter);
} catch (Exception e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.fetchButton :
aantalPersonen = et.getText().toString();
if (aantalPersonen.trim().equals("")) {
Toast.makeText(this, "Gelieve het aantal personen in te geven", Toast.LENGTH_SHORT).show();
return;
}
else
{
new task().execute();
break;
}
}
}
}
It is my first Android code ever, so besides my question it is possible that this code can be made better.
What I would like to do is to show ALL data, nicely, which was gotten from the website. But, as a ListView can not contain the ID and other data, I'm wondering if I can reuse the data in the JSONObject to be shown in next screen (on click of ListView item) ?
Greetings and thanks in advance,
Davy
Create variables for which you want to store information and loop through JsonArray and get each JsonObject and parse/extract information that you need and store it in variables.
here is sample code to iterate JsonArray //Here response is JsonArray
Create Simple class like
public class PersonInfo{
String name,address; //Create variables of your requirement.
//Add Getter Setter Methods for these variables
}
//End of class PersonInfo
ArrayList<PersonInfo> persons = new ArrayList<PersonInfo>();
PersonInfo person;
JSONObject product;
try
{
for (int j = 0; j < response.length(); j++)
{
person = new Person();
product = response.getJSONObject(j);
person.name = product.getString("JSON_KEY_NAME"); //like these assign values to each variable of PersonInfo class
//Other values initialization
}
persons.add(person); // Add PersonInfo object to ArrayList
}
catch (Exception e)
{
e.printStackTrace();
}
something like that .
you can get json values upon your requirments.
This is just sample code .
You could
save the JSON and parse it again later (you would have to do a lot of parsing)
save the data you parse from the json
in sharedpreferences (only if small amount of data)
in a local sqlite db (probably cleanest approach with best user experience, but a lot of work since you have to create a class that does all the db CRUD operations)
It depends on your data. For user preferences I would use SharedPreferences, for larger amounts a local DB. Also you could create some objects to store the data you need, maybe as signletons or something, and parse the stored JSONs everytime you start the app.
See the google docs on data storage for reference.
To save data you are getting in background task you have to use shared preferences.
Refer this link to get details about shared preferences.
To pass data to next page you have to use following code :
Intent intent = new Intent( currentActivity.this, NextActivity.class);
intent.putExtra("key", "value");
startActivity(intent);
On nextActivity.java add following code inside onCreate()
Intent currentPageIntent = getIntent();
String strValue = currentPageIntent.getStringExtra("key");
If you are having any other data type than string you have to use other method instead of getStringExtra()
To get id of item clicked, you can use following code :
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
try {
JSONArray jsonArray = new JSONArray(jsonData);
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
if (i == id) {
//Add your code here
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally { }
}
});
Note that you have to process jsonData on your own. This is just sample code I used in one of my porjects.

Binding json data in spinner

package com.android.housingapp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.housingapp.helper.JSONParser;
import com.android.housingapp.helper.ListViewAdapter;
import com.android.housingapp.helper.ListViewAdapterComplaints;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
public class BillsandDuesSpinner extends Activity{
Button btnaddyear,btnnext;
String name_array[];
Spinner yearspinner, spmonth;
String year_id,year,month,own_id;
String url;
JSONParser jParser ;
JSONArray montharray= null;
Context context=this;
int success=0;
JSONObject json;
ArrayList<HashMap<String, String>> monthList;
List<NameValuePair> params = new ArrayList<NameValuePair>();
ProgressDialog pDialog;
private static final String TAG_SUCCESS = "success";
private static final String TAG_DUE_MAIN= "all_year_list";
private static final String TAG_DUE_ID = "year_id";
private static final String TAG_DUE_MON = "month";
private static final String TAG_DUE_YEAR = "year";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.billsandduesspinner);
btnaddyear=(Button)findViewById(R.id.btnaddyear);
btnnext=(Button)findViewById(R.id.btnnext);
yearspinner=(Spinner)findViewById(R.id.spyear);
spmonth=(Spinner)findViewById(R.id.spmonth);
own_id=getIntent().getExtras().getString("own_id");
monthList =new ArrayList<HashMap<String, String>>();
new BindYear().execute();
ArrayAdapter<CharSequence> adapter=ArrayAdapter.createFromResource(this,R.array.month,android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spmonth.setAdapter(adapter);
url="http://10.0.2.2:80/Android/HousingApp/get_due_mon_spinner.php";
btnaddyear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(getApplicationContext(),NewYear.class);
startActivity(i);
}
});
btnnext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(BillsandDuesSpinner.this,TypesofBills.class);
startActivity(i);
}
});
}
class BindYear extends AsyncTask<String,String,String>{
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(BillsandDuesSpinner.this);
pDialog.setMessage("Loading complains. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
// contactList = new ArrayList<HashMap<String, String>>()
// Creating JSON Parser instance
jParser = new JSONParser();
// getting JSON string from URL
try {
json = jParser.getJSONFromUrl(url);
if(json.has(TAG_DUE_MAIN))
{
// Getting Array of Contacts
montharray = json.getJSONArray(TAG_DUE_MAIN);
name_array = new String[montharray.length()];
// looping through All Contacts
for(int i = 0; i < montharray.length(); i++){
JSONObject c = montharray.getJSONObject(i);
// Storing each json item in variable
year_id=c.getString(TAG_DUE_ID);
month = c.getString(TAG_DUE_MON);
year = c.getString(TAG_DUE_YEAR);
name_array[i] = c.getString(TAG_DUE_YEAR);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_DUE_ID,year_id );
map.put(TAG_DUE_MON,month);
map.put(TAG_DUE_YEAR,year );
// adding HashList to ArrayList
monthList.add(map);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// Pass the results into ListViewAdapter.java
try{
if(json.has(TAG_DUE_MAIN))
{
ArrayAdapter<String> adapter = new ArrayAdapter<String> (BillsandDuesSpinner.this, android.R.layout.simple_spinner_item, name_array);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
yearspinner.setAdapter(adapter);
}
else{
Toast.makeText(BillsandDuesSpinner.this,"No year is available now.Please add one.",Toast.LENGTH_SHORT).show();
}
}catch(Exception e)
{
e.printStackTrace();
}
pDialog.dismiss();
}
}
}
Here is a simple code of binding json data in a spinner.My php code for fetching json data is absolutely alright.The problem is whenever I try to bind json data in the spinner,at first the app crashes(showing null pointer exception) or it bind nothing into the spinner.But when I again click the button which will bind the json data into the spinner (it resides into another activity), after crashing(not running the app again),then the data is binded to the spinner sucessfully.So what is the problem??why the data is not binding at the first time??
Try this..
Initialize the url before calling BindYear BindYear
url="http://10.0.2.2:80/Android/HousingApp/get_due_mon_spinner.php";
new BindYear().execute();
Because at the first time url is empty. That time you will get Exception in doInBackground os json is null then onPostExecute will run that time you are accessing from json as json.has that time you will get NPE
as #Hariharan answered that is the porblem you are getting NPE for first time.So the best approach would be as follows,
url="http://10.0.2.2:80/Android/HousingApp/get_due_mon_spinner.php";
new BindYear().execute(url);
and in doInBackground() change as follows,
json = jParser.getJSONFromUrl(params[0]);

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 get a specific String out from a ListView Item

What I'm trying to do
Hello Guys, I'm creating an App for a friend of mine, i simply show his Channel in my App. I get the Data of the Videos over JSON.
Now I found a Problem. When I filled the data into my ListView over the SimpleListAdapter and try to get it over an OnItemClickListner and retrieve them over lv.getItemAtPosition(position); I get all data which is stored in the specific row. But I only need the Link/Url I saved in that field.
Question
Like you read I got more than one information in my ListView to be exactly there are four Strings (Thumb,Title, Content, Link). But I only need to get the String of the Link, how can I do this, down here you find the Code.
Code
test2.java
package de.stepforward;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.ListActivity;
import android.database.Cursor;
import android.media.RingtoneManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class test2 extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String result = "";
String line = null;
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
//get the Data from URL
try{
URL url = new URL("http://gdata.youtube.com/feeds/mobile/users/TheStepForward/uploads?alt=json&format=1");
URLConnection conn = url.openConnection();
StringBuilder sb = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
//read d response till d end
while ((line = rd.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
Log.v("log_tag", "Append String " + result);
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try{
JSONObject json = new JSONObject(result);
JSONObject feed = json.getJSONObject("feed");
JSONArray entrylist = feed.getJSONArray("entry");
for(int i=0;i<entrylist.length();i++){
//Get Title
JSONObject movie = entrylist.getJSONObject(i);
JSONObject title = movie.getJSONObject("title");
String txtTitle = title.getString("$t");
Log.d("Title", txtTitle);
//Get Description
JSONObject content = movie.getJSONObject("content");
String txtContent = content.getString("$t");
Log.d("Content", txtContent);
//Get Link
JSONArray linklist = movie.getJSONArray("link");
JSONObject link = linklist.getJSONObject(0);
String txtLink = link.getString("href");
Log.d("Link", txtLink);
//Get Thumbnail
JSONObject medialist = movie.getJSONObject("media$group");
JSONArray thumblist = medialist.getJSONArray("media$thumbnail");
JSONObject thumb = thumblist.getJSONObject(2);
String txtThumb = thumb.getString("url");
Log.d("Thumb", txtThumb.toString());
//String Array daraus machen und in Hashmap füllen
HashMap<String, String> map = new HashMap<String, String>();
map.put("Thumb", txtThumb);
map.put("Title", txtTitle);
map.put("Content", txtContent);
map.put("Link", txtLink);
mylist.add(map);
}
//ListView füllen
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.lit,
new String[] { "Thumb","Title","Content","Link"},
new int[] { R.id.img_video,R.id.txt_title,R.id.txt_subtitle});
setListAdapter(adapter);
//OnClickLister um Youtube-Video zu öffnen
final ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
lv.getItemAtPosition(position);
}
});
}catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
}
}
Thank you in Advance
final ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Map<String, String> map = mylist.get(position);
String link = map.get("Link");
}
});
Better way is to wrap your information in an Object and download the data from internet and make an Object and add it to any ArrayList.
For Example:
You will make an Java Object class. say: VideoInfo
public class VideoInfo
{
String title, content, link, thumb;
// define there setter getter
// also a constructor with these params
public VideoInfo(String title,String content,String link,String thumb)
{
//set Values accordingly
}
}
make a class level ArrayList
ArrayList<VideoInfo> myList = new ArrayList<VideoInfo>();
and when you get data from server parse it and save it like this way:
myList.add(new VideoInfo(txtTitle, txtContent, txtLink, txtThumb));
You will need customization of Adapter (e.g override getView()) to set data from your custom Ojbect (VideoInfo).
and then in your ListActivity in OnItemClickListener you will get your desired object like this way:
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// you have class level ArrayList myList.
myList.get(position).getLink(); //getLink() will be the getter of you field link in VideoInfo
}
lv.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
HashMap<String, String> selectedHashMapObject = (HashMap<String, String>)lv.getItemAtPosition(position);
String selectedLink = selectedHashMapObject.get("Link");
}
For example, you can do something similar like this:
for(int i = 0; i < ((ListView)lv).getItemCount(); i++){
Map<String, String> currentView = (Map<String, String>) ((ListView)lv).getItemAtPosition(i);
String cVId = currentView.get("id");
}
i think you can use this
http://developer.android.com/reference/android/widget/CursorAdapter.html#getItem(int).
Cursor cursor = (Cursor) simple.getItem(position);
// retrieve the data from the cursor

setOnClickListener - application stopped unexpectedly

As soon as I use setOnClickListener for a button in my code, when I start the application it says the application has stopped unexpectedly
package example.khumbayatabbed;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class Category extends ListActivity{
int categ=0;
String[] categories = new String[100];
Button button1;
EditText edittext1;
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
edittext1= (EditText) findViewById(R.id.edittext);
button1 = (Button) findViewById(R.id.button);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
edittext1.setText("");
Toast.makeText(getApplicationContext(), "Hello",
Toast.LENGTH_SHORT).show();
}
});
// setContentView(R.layout.main);
// Create a crude view - this should really be set via the layout resources
// but since its an example saves declaring them in the XML.
// Set the text and call the connect function.
//call the method to run the data retreival
final String KEY_121 = "http://myurl";
getServerData(KEY_121);
if(mylist.isEmpty())
Toast.makeText(getApplicationContext(), "No more sub categories",
Toast.LENGTH_SHORT).show();
else
display(mylist);
}
private void getServerData(String jason) {
mylist = new ArrayList<HashMap<String, String>>();
InputStream is = null;
String returnString="";
String result = "";
//mylist.clear();
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(jason);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","url: "+json_data.getString("url")+
", name: "+json_data.getString("value")
);
//Get an output to the screen
categories[categ++]=json_data.getString("value");
map.put("name", json_data.getString("value"));
map.put("url", json_data.getString("url"));
mylist.add(map);
returnString += jArray.getJSONObject(i).getString("url") + "\n";
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
private void display(ArrayList<HashMap<String, String>> list)
{
ListAdapter adapter=new SimpleAdapter(this,list,R.layout.list_item2, new String[] {"name"}, new int[]{R.id.cat_name});
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
#SuppressWarnings("unchecked")
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, String> tmp = new HashMap<String, String>();
tmp=(HashMap<String, String>)parent.getItemAtPosition(position);
String cat_url=tmp.get("url");
final String KEY_121 = "http://myurl/"+cat_url;
getServerData(KEY_121);
if(mylist.isEmpty())
Toast.makeText(getApplicationContext(), "No more sub categories",
Toast.LENGTH_SHORT).show();
else
display(mylist);
}
});
}
}
This is code for my main page:
public class Khumbayatabbed extends TabActivity
{ /** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Resources res = getResources(); // Resource object to get Drawables
TabHost tabHost = getTabHost(); // The activity TabHost
TabHost.TabSpec spec; // Reusable TabSpec for each tab
Intent intent; // Reusable Intent for each tab
// Create an Intent to launch an Activity for the tab (to be reused)
intent = new Intent().setClass(this, Category.class);
// Initialize a TabSpec for each tab and add it to the TabHost
spec = tabHost.newTabSpec("category").setIndicator("Category",
res.getDrawable(R.drawable.ic_tab))
.setContent(intent);
tabHost.addTab(spec);
// Do the same for the other tabs
intent = new Intent().setClass(this, Event.class);
spec = tabHost.newTabSpec("event").setIndicator("Event",
res.getDrawable(R.drawable.ic_tab))
.setContent(intent);
tabHost.addTab(spec);
tabHost.setCurrentTab(0);
}
}
The main.xml looks like this:
You didn't wrtie setContentView for your layout.So you can't access Your editText1 and same for the button1.
write something like
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
In your Main Page to call this use
Intent myIntent = new Intent(MainPage.this,Category.class);
MainPage.this.startActivity(myIntent);

Categories

Resources