want to send listview data to another activity in android - android

package com.example.selflistview;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView text;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
connect();
}
private void connect() {
String data;
List<String> r = new ArrayList<String>();
ArrayAdapter<String>adapter=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,r);
ListView list=(ListView)findViewById(R.id.listView1);
try {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://localhost/listview.php");
HttpResponse response = client.execute(request);
HttpEntity entity=response.getEntity();
data=EntityUtils.toString(entity);
Log.e("STRING", data);
try {
JSONArray json=new JSONArray(data);
for(int i=0;i<json.length(); i++)
{
JSONObject obj=json.getJSONObject(i);
String name=obj.getString("name");
String year=obj.getString("year");
String age=obj.getString("age");
Log.e("STRING", name);
r.add(name);
//r.add(year);
//r.add(age);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
// TODO Auto-generated method stub
//final String item = (String) arg0.getItemAtPosition(arg2);
Toast.makeText(getBaseContext(), "arg2 : "+arg2, Toast.LENGTH_SHORT).show();
Intent view_det = new Intent(getBaseContext(),ViewDetail.class);
view_det.putExtra("position",arg2);
startActivity(view_det);
}
});
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ClientProtocolException e) {
Log.d("HTTPCLIENT", e.getLocalizedMessage());
} catch (IOException e) {
Log.d("HTTPCLIENT", e.getLocalizedMessage());
}
}
}
I want to send Year, name and age to another activity, i am able to get the positions at intent but not the other values. please help...
I am able to see those values in list., but not able to call at intent section.
Your help will be appreciated..

This might help
Public class MainActivity extends Activity {
TextView text;
List<String> r; //define list here
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
connect();
}
private void connect() {
String data;
r = new ArrayList<String>();
try {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://localhost/listview.php");
HttpResponse response = client.execute(request);
HttpEntity entity=response.getEntity();
data=EntityUtils.toString(entity);
Log.e("STRING", data);
try {
JSONArray json=new JSONArray(data);
for(int i=0;i<json.length(); i++)
{
JSONObject obj=json.getJSONObject(i);
String name=obj.getString("name");
String year=obj.getString("year");
String age=obj.getString("age");
Log.e("STRING", name);
r.add(name);
//r.add(year);
//r.add(age);
}
ArrayAdapter<String>adapter=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,r);
ListView list=(ListView)findViewById(R.id.listView1);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
// TODO Auto-generated method stub
//final String item = (String) arg0.getItemAtPosition(arg2);
Toast.makeText(getBaseContext(), "arg2 : "+arg2, Toast.LENGTH_SHORT).show();
Intent view_det = new Intent(getBaseContext(),ViewDetail.class);
view_det.putExtra("position",arg2);
String name = r.get(arg2);//add this line to get name from the arraylist of that position
JSONObject obj=json.getJSONObject(arg2); //you can get other two values from json object
String year=obj.getString("year");
String age=obj.getString("age");
view_det.putExtra("name",name); //add this
view_det.putExtra("year",year); //add this
view_det.putExtra("age",age); //add this
startActivity(view_det);
}
});
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ClientProtocolException e) {
Log.d("HTTPCLIENT", e.getLocalizedMessage());
} catch (IOException e) {
Log.d("HTTPCLIENT", e.getLocalizedMessage());
}
}
}

Related

OnItemClickListner is not working in AutoCompleteTextView

I used AutoCompleteTextView, When i select any item from it and set Toast in the item, it is displaying another data like if i select first item then it will toast first item and when i select second item it will toast first item only.
Here is my code:
MainActivity.java
package com.example.sachin.addvisit;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MainActivity extends Activity {
InputStream is=null;
String result=null;
String line=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new DownloadJSON().execute();
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/autocomplete.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("Pass 1", "connection success ");
} catch (Exception e) {
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address", Toast.LENGTH_LONG).show();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("Pass 2", "connection success ");
} catch (Exception e) {
Log.e("Fail 2", e.toString());
}
try {
JSONArray JA = new JSONArray(result);
JSONObject json = null;
final String[] str1 = new String[JA.length()];
for (int i = 0; i < JA.length(); i++) {
json = JA.getJSONObject(i);
str1[i] = json.getString("name");
}
final AutoCompleteTextView text = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
final List<String> list = new ArrayList<String>();
for (int i = 0; i < str1.length; i++) {
list.add(str1[i]);
}
Collections.sort(list);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.my_list_item, list);
// dataAdapter.setDropDownViewResource(android.R.layout.simple_list_item_1);
text.setThreshold(1);
text.setAdapter(dataAdapter);
text.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int abc, long l) {
Toast.makeText(getApplicationContext(), list.get(abc).toString(),Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
Log.e("Fail 3", e.toString());
}
}
}
}
Here autocomplete.php
<?php
$host='127.0.0.1';
$uname='root';
$pwd='';
$db='android';
$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
mysql_select_db($db,$con) or die("db selection failed");
$r=mysql_query("select * from class",$con);
while($row=mysql_fetch_array($r))
{
$cls[]=$row;
}
print(json_encode($cls));
mysql_close($con);
?>
Please Help me out from this..
add this :-
text.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),(CharSequence)arg0.getItemAtPosition(arg2), Toast.LENGTH_LONG).show();
}
});

I want to fetch image from mysql to android listview using php json...?

> This is my MainActivity.java That receives all json data from the php file and converts into string format and print it in listview using string array but i have problem with bitmap image array
I want to add multiple items in listview like textview and image i dont have problem with textview it displays properly but with image it is not done
package com.demo.php.listview;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
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.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore.Images;
import android.util.Base64;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnItemClickListener {
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb = null;
ArrayList<String> al = new ArrayList<String>();
ArrayList<String> al1 = new ArrayList<String>();
ArrayList<String> al2 = new ArrayList<String>();
ArrayList<String> al3=new ArrayList<String>();
String targetmonth;
String targetyear;
String targetamount;
String Dphoto;
// int responseCode;
//int listItemCount=0;
ListView listview ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(Color.WHITE);
setTitleColor(Color.rgb(0x74, 0, 0x37));
setTitle("Doctor's List");
requestWindowFeature(Window.FEATURE_RIGHT_ICON);
setContentView(R.layout.main);
listview = (ListView) findViewById(R.id.listView1);
listview.setOnItemClickListener(this);
new LoadData().execute();
}
private class LoadData extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
#Override
// can use UI thread here
protected void onPreExecute() {
this.progressDialog = ProgressDialog.show(MainActivity.this, ""," Loading...");
}
#Override
protected void onPostExecute(final Void unused) {
try{
listview.setAdapter(new DataAdapter(MainActivity.this,
al.toArray(new String[al.size()]),
al1.toArray(new String[al1.size()]),
al2.toArray(new String[al2.size()]),
al3.toArray(new Bitmap[al3.size()])));
this.progressDialog.dismiss();
}
catch(Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// HTTP post
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
HttpClient httpclient = new DefaultHttpClient();
try{
HttpPost httppost = new HttpPost("http://10.0.2.2/android/test.php");
StringEntity se = new StringEntity("envelope",HTTP.UTF_8);
httppost.setEntity(se);
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 3000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
//buffered reader
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 80);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
}
catch(Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
try{
jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
targetamount=json_data.getString("DName");
targetmonth=json_data.getString("Dspl");
targetyear = json_data.getString("Dedu");
Dphoto = json_data.getString("Dphoto");
al.add(targetmonth);
al1.add(targetyear);
al2.add(targetamount);
al3.add(Dphoto);
//listItemCount=al2.size();
}
}
catch(JSONException e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
} catch (ParseException e) {
// Log.e("log_tag", "Error in http connection" + e.toString());
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
catch (Exception e) {
// Log.e("log_tag", "Error in http connection" + e.toString());
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
return null;
}
}
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
Intent intent = new Intent(this, NextItem.class);
startActivity(intent);
}
}
>This is my DataAdapter
I am not getting the image in Listview I am little bit confuse about the image bitmap array please helps with that bitmap
package com.demo.php.listview;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.provider.MediaStore.Images;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class DataAdapter extends BaseAdapter {
Context mContext;
private LayoutInflater mInflater;
String targetmonth;
String targetyear;
String targetamount;
//Bitmap Dphoto1;
String[] month;
String[] year;
String[] amount;
String[] Dphoto1;
Bitmap[] Dphoto2;
private String src;
public DataAdapter(Context c, String[] month, String[] year, String[] amount,Bitmap[] Dphoto2) {
//this.sta = sta;
Bitmap[] = (Bitmap[]) getBitmapFromURL(Dphoto2);
this.month = month;
this.year = year;
this.amount = amount;
this.Dphoto2=Dphoto2;
mContext = c;
mInflater = LayoutInflater.from(c);
}
public int getCount() {
return month.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.doctor, parent, false);
holder = new ViewHolder();
holder.month = (TextView) convertView
.findViewById(R.id.Dname);
holder.year = (TextView) convertView.findViewById(R.id.Dspl);
holder.amount = (TextView) convertView
.findViewById(R.id.Dedu);
holder.Dphoto2=(ImageView)convertView.findViewById(R.id.Dphoto2);
if (position == 0) {
convertView.setTag(holder);
}
} else {
holder = (ViewHolder) convertView.getTag();
}
try {
holder.month.setText(month[position]);
holder.year.setText(year[position]);
holder.amount.setText(amount[position]);
holder.Dphoto2.setImageBitmap(Dphoto2[position]);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return convertView;
}
private Object getBitmapFromURL(Bitmap[] dphoto2) {
// TODO Auto-generated method stub
try{
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
}
static class ViewHolder {
public ImageView Dphoto2;
public TextView Dphoto1;
public ImageView Dphoto;
TextView month;
TextView year, amount;
}
public class ImageLoadTask {
public void execute(String dphoto1) {
// TODO Auto-generated method stub
}
}}
The JSON text will deliver a base64 encoded bitmap or jpg.
ArrayList<String> al3=new ArrayList<String>();
change that to:
ArrayList<Bitmap> al3=new ArrayList<Bitmap>();
And in the loop change:
al3.add(Dphoto);
to:
Bitmap bitmap = decodeBitmapFromBase64 (Dphoto);
al3.add(bitmap);
Remove:
Bitmap[] = (Bitmap[]) getBitmapFromURL(Dphoto2); // does not even compile!
You have to implement a function decodeBitmapFromBase64(). You can find code for it on this site.
Remove all Toast()s from doInBackground. They are not allowed there. Put them in onPostExecute instead.

How to display image from mysql database?

I have code to display all data from MySQL databae also i have a image field in MySQL database which have image names.how can i display image from database(The image is located at localhost folder). Im new in android so please help me. Here is my code if u can alter my required code then it will be a great help.
JAVA
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.Fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class News_events extends Fragment {
private String jsonResult;
private String url = "http://192.168.2.7/crescentnews/select.php";
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
InputStream is=null;
String result=null;
String line=null;
int code;
public News_events(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_news_events, container, false);
accessWebService();
return rootView;
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(1);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
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(getActivity().getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
display();
}
}// 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 display() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("news_details");
LinearLayout MainLL= (LinearLayout)getActivity().findViewById(R.id.newslayout);
//LinearLayout headLN=(LinearLayout)findViewById(R.id.headsection);
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
final String head = jsonChildNode.optString("title");
final String details = jsonChildNode.optString("text");
final String date = jsonChildNode.optString("date");
//final String time = jsonChildNode.optString("time");
TextView headln = new TextView(this.getActivity());
headln.setText(head); // News Headlines
headln.setTextSize(20);
headln.setTextColor(Color.BLACK);
headln.setGravity(Gravity.CENTER);
headln.setBackgroundResource(R.drawable.menubg);
headln.setPadding(10, 20, 10, 0);
headln.setWidth(100);
headln.setClickable(true);
headln.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Toast.makeText(getBaseContext(), head, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity().getApplicationContext(),MainActivity.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
// intent.putExtra("time",time.toString());
startActivity(intent);
}
});
ImageView photo=new ImageView(this.getActivity());
//dateln.setBackgroundColor(Color.parseColor("#f20056"));
photo.setBackgroundColor(Color.parseColor("#000000"));
photo.setPadding(0, 0, 10, 10);
photo.setClickable(true);
TextView dateln = new TextView(this.getActivity());
dateln.setText(date); // News Headlines
dateln.setTextSize(12);
dateln.setTextColor(Color.BLACK);
dateln.setGravity(Gravity.RIGHT);
//dateln.setBackgroundColor(Color.parseColor("#f20056"));
dateln.setBackgroundColor(0x00000000);
dateln.setPadding(0, 0, 10, 10);
dateln.setWidth(100);
dateln.setClickable(true);
dateln.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity().getApplicationContext(), MainActivity.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
// intent.putExtra("time",time.toString());
startActivity(intent);
}
});
View sep=new View(this.getActivity());
sep.setBackgroundColor(Color.parseColor("#252525"));
sep.setMinimumHeight(10);
TextView detailsln = new TextView(this.getActivity());
detailsln.setText(details); // News Details
detailsln.setTextSize(12);
detailsln.setTextColor(Color.BLACK);
detailsln.setGravity(Gravity.LEFT);
detailsln.setPadding(10, 10, 10, 10);
MainLL.addView(headln);
MainLL.addView(dateln);
MainLL.addView(photo);
MainLL.addView(detailsln);
MainLL.addView(sep);
detailsln.setClickable(true);
detailsln.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity().getApplicationContext(), MainActivity.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
// intent.putExtra("time",time.toString());
startActivity(intent);
}
});
}
} catch (JSONException e) {
Toast.makeText(getActivity().getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
}
}
save your image url in db (if they are in a same folder on your host choose a base url and save only image name)
after fetching your data , there are alot of library for display images such as :
Picasso
A powerful image downloading and caching library for Android

Android-Json parser not able to display data retrieved from back end

I am new to android. I am implementing a project in which I want to get the data from the back end and display on my android screen.
The Json I am trying to call is:-
[{"admin":null,"card_no":"8789","created_at":"2013-04-09T12:55:54Z","deleted":0,"email":"dfds#fgfd.com","entered_by":null,"first_name":"Gajanan","id":8,"last_name":"Bhat","last_updated_by":null,"middle_name":"","mobile":87981,"updated_at":"2013-04-13T05:26:25Z","user_type_id":null},{"admin":{"created_at":"2013-04-10T09:02:00Z","deleted":0,"designation":"Sr software Engineer","email":"admin#qwe.com","first_name":"Chiron","id":1,"last_name":"Synergies","middle_name":"Sr software Engineer","office_phone":"98789765","super_admin":false,"updated_at":"2013-04-10T12:03:04Z","username":"Admin"},"card_no":"66","created_at":"2013-04-08T09:47:15Z","deleted":0,"email":"rajaarun1991","entered_by":1,"first_name":"Arun","id":1,"last_name":"Raja\n","last_updated_by":1,"middle_name":"Nagaraj","mobile":941,"updated_at":"2013-04-08T09:47:15Z","user_type_id":1}]
My JsonParser.java is as follows:-
package com.example.library;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONArray jarray = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONArray getJSONFromUrl(String url) {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e("==>", "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// try parse the string to a JSON object
try {
jarray = new JSONArray( builder.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jarray;
}
}
/* public void writeJSON() {
JSONObject object = new JSONObject();
try {
object.put("name", "");
object.put("score", new Integer(200));
object.put("current", new Double(152.32));
object.put("nickname", "Programmer");
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println(object);
}
*/
And my activity.java is as follows:-
package com.example.library;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class SecondActivity extends Activity
{
private Context context;
private static String url = "http://192.168.0.100:3000/users.json";
private static final String TAG_ID = "id";
private static final String TAG_FIRST_NAME = "first_name";
private static final String TAG_MIDDLE_NAME = "middle_name";
private static final String TAG_LAST_NAME = "last_name";
// private static final String TAG_POINTS = "experiencePoints";
ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
ListView lv ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new ProgressTask(SecondActivity.this).execute();
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
public ProgressTask(SecondActivity secondActivity) {
Log.i("1", "Called");
context = secondActivity;
dialog = new ProgressDialog(context);
}
/** progress dialog to show user that the backup is processing. */
/** application context. */
private Context context;
protected void onPreExecute() {
this.dialog.setMessage("Progress start");
this.dialog.show();
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
ListAdapter adapter = new SimpleAdapter(context, jsonlist,
R.layout.list_item, new String[] { TAG_ID, TAG_FIRST_NAME,
TAG_MIDDLE_NAME, TAG_LAST_NAME }, new int[] {
R.id.id, R.id.first_name, R.id.middle_name,
R.id.last_name });
setListAdapter(adapter);
// selecting single ListView item
lv = getListView();
}
private void setListAdapter(ListAdapter adapter) {
// TODO Auto-generated method stub
}
protected Boolean doInBackground(final String... args) {
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url);
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
String id = c.getString(TAG_ID);
String first_name = c.getString(TAG_FIRST_NAME);
String middle_name = c.getString(TAG_MIDDLE_NAME);
String last_name = c.getString(TAG_LAST_NAME);
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_FIRST_NAME, first_name);
map.put(TAG_MIDDLE_NAME, middle_name);
map.put(TAG_LAST_NAME, last_name);
jsonlist.add(map);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
}
public ListView getListView() {
// TODO Auto-generated method stub
return null;
}
}
I am not able to show anything on the emulators for users,whereas I am able to fetch the data from the server
Actually in the project I want to display all the users present in the library.I am accessing the server which is on Ubuntu.
The following message is displayed on the console(Terminal):-
Started GET "/users.json" for 192.168.0.104 at 2013-05-05 22:05:01 -0700
Processing by UsersController#index as JSON
User Load (0.4ms) SELECT "users".* FROM "users" WHERE (users.deleted = 0) ORDER BY users.id DESC
Admin Load (0.3ms) SELECT "admins".* FROM "admins" WHERE "admins"."id" = 1 AND (admins.deleted = 0) ORDER BY admins.id DESC LIMIT 1
Completed 200 OK in 4ms (Views: 2.1ms | ActiveRecord: 0.6ms)
[2013-05-05 22:05:01] WARN Could not determine content-length of response body. Set content-length of the response or set Response#chunked = true
However i am not able to display the data on the android screen/emulator.
Please help me with this.
I missed your setAdapterList()method.
Any error for your json pasers? and can you put your activity which is inherited from SecondActivity?
//modify getListView
public ListView getListView() {
// TODO Auto-generated method stub
listView = (ListView)findViewById(r.your.listview);
return listView;
}
//modify setListAdapter
private void setListAdapter(ListAdapter adapter) {
// TODO Auto-generated method stub
lv.setAdapter(adapter);
}

Java Android Eclipse

Hey all..I am struck here, I have to display news in a separate list view from a news link web site, but when I debug the cursor goes null. How do I resolve this? Here is my code
package adn.GoMizzou.NB;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class NB extends ListActivity {
public static final String URL = "http://nbsubscribe.missouri.edu/news-releases/feed/atom/";
private String msg;
private boolean success;
private int scrollIndex;
private int scrollTop;
private HttpClient httpClient;
private NBDBAdapter dbAdapter;
private ProgressDialog pDialog;
private Context ctx = this;
private SharedPreferences prefs;
private SharedPreferences.Editor prefsEditor;
//private Cursor cur;
private Cursor q;
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg){
pDialog.dismiss();
fillList();
}
};
/* ACTIVITY METHODS */
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.nb);
setTitle("News");
q=null;
scrollIndex = 0;
dbAdapter = new NBDBAdapter(this);
dbAdapter.open();
registerForContextMenu(getListView());
getData();
}
public void getData(){
pDialog = ProgressDialog.show(this, "", "Loading. Please wait...", true);
new Thread(){
public void run(){
dbAdapter.deleteAll();
dbAdapter.close();
doPost(URL, "");
dbAdapter.open();
handler.sendEmptyMessage(0);
}
}.start();
}
public boolean doPost(String url, String postMsg){
HttpResponse response = null;
createHttpClient();
try {
URI uri = new URI(url);
HttpPost httppost = new HttpPost(uri);
StringEntity postEntity = new StringEntity(postMsg);
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
postEntity.setContentType("application/x-www-form-urlencoded");
httppost.setEntity(postEntity);
response = httpClient.execute(httppost);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(response == null){
msg = "No internet connection.";
return false;
}
if(response.getStatusLine().getStatusCode()!= 200){
msg = "Server error.";
return false;
}
return doParse(response);
}
public void createHttpClient(){
if(httpClient == null){
httpClient = new DefaultHttpClient();
}
}
public boolean doParse(HttpResponse response){
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
NBParser respHandler = new NBParser(ctx);
xr.setContentHandler(respHandler);
HttpEntity entity = response.getEntity();
BufferedHttpEntity buffEntity = new BufferedHttpEntity(entity);
xr.parse(new InputSource(buffEntity.getContent()));
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
if(e.getMessage().toString().contains("nothing found")){
msg = e.getMessage().toString();
return false;
}
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Cursor c = q;
q.moveToPosition(position);
//Intent i = new Intent(this, NB.class);
//i.putExtra("link", c.getString(c.getColumnIndexOrThrow(NBDBAdapter.NB_LINK)));
String newsLinkString = q.getString(q.getColumnIndexOrThrow(NBDBAdapter.NB_LINK));
TextView linkTV = (TextView) v.findViewById(R.id.rowlink);
newsLinkString = linkTV.getText().toString();
if (newsLinkString.startsWith("http://")){
Uri uri = Uri.parse(newsLinkString);
Intent i = new Intent(this, NB.class);
// Save ListView position
i.putExtra("link", c.getString(c.getColumnIndexOrThrow(NBDBAdapter.NB_LINK)));
startActivity(i);
}
}
//else {
//showLinkError();
//}
// Sends an error message to the user if the news item link is malformed
//public void showLinkError() {
//Toast.makeText(getApplicationContext(), "Error - Link to story unavailable with news source could not load the News Story", Toast.LENGTH_SHORT).show();
//}
private void showLinkError() {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Error - Link to story unavailable with news source could not load the News Story", Toast.LENGTH_SHORT).show();
}
public void fillList(){
if(!success) {
TextView emptyView = (TextView) findViewById(android.R.id.empty);
emptyView.setText(msg);
msg = "";
}
if(!dbAdapter.isOpen()) dbAdapter.open();
Cursor cursor = dbAdapter.fetchAll();
startManagingCursor(cursor);
String [] from = new String[] { dbAdapter.NB_AUTHOR, dbAdapter.NB_TITLE,dbAdapter.NB_LINK };
int[] to = new int[] { R.id.rowAuthor, R.id.rowTitle, R.id.rowlink };
SimpleCursorAdapter list = new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
setListAdapter(list);
}
}
Which cursor are you talking about?
If it's when you click on an item it's because you assign the cursor q null in onCreate and then call moveToPosition on it in onListItemClick.

Categories

Resources