setOnClickListener - application stopped unexpectedly - android

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

Related

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

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.

Taking data parsed with JSON and displaying it as text in Android

I am using JSON to access my mySQL database and then return product information such as the UPCA, Product, and Company. I am able to get the information to display in grey text but not appear in text view. How can I get it to appear in text view. I have reviewed other questions but I cannot find one that would specifically help me. Any information on how to do this would be great. Maybe I am missing something? Thank you in advance
This is my Main file package
net.example.glutefree;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.widget.Button;
import android.widget.EditText;
//import android.widget.TextView;
import android.view.View;
import android.view.View.OnClickListener;
//Links GLUTEFREE with NEWACTIVITY
public class GluteFree extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.glute_free);
mMyEditText = (EditText) findViewById(R.id.editText1);
Button pressToScan = (Button) findViewById(R.id.button1);
pressToScan.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent data = new Intent("com.google.zxing.client.android.SCAN");
data.putExtra("com.google.zxing.client.android.SCAN.SCAN_MODE",
"QR_CODE_MODE");
setResult(RESULT_OK, data);
startActivityForResult(data, 0);
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
String UPC = null;
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
UPC = data.getStringExtra("SCAN_RESULT");
// moved here
Intent i = new Intent("net.example.glutefree.Networking");
i.putExtra("UPCA", UPC);
startActivity(i);
EditText tv = (EditText) findViewById(R.id.editText1);
tv.setText(UPC);
// Handle successful scan
} else if (resultCode == RESULT_CANCELED) {
// Handle cancel
}
}
}
// Click this Link to open Links Page
public void onClickLinks(View view) {
;
}
//Click this Link to open the Previous Result
public void onClickResult(View view) {
startActivity(new Intent("net.example.glutefree.Networking"));
}
//Manually Search the UPC that is in the box
//FIND CODE TO MAKE THAT WORK
private EditText mMyEditText;
public void onClickSearch(View view) {
String UPC = mMyEditText.getText().toString();
Intent intent = new Intent(this, Networking.class);
intent.putExtra("UPCA", UPC); //text is some key used to retrieve value in NextActivity
startActivity(intent);
}
}
This is my Database connection file.
package net.example.glutefree;
import android.app.Activity;
import android.os.Bundle;
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.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import android.widget.TextView;
public class Networking extends Activity{
TextView txt;
int request_Code = 1;
//called when activity is first created
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_networking);
txt = new TextView(getApplicationContext());
// Set the text and call the connect function.
txt.setText("Connecting...");
//call the method to run the data retrieval
new Thread() {
public void run() {
final String data = getServerData(KEY_121);
if (data != null)
runOnUiThread(new Runnable()
{
public void run()
{
txt.setText(data);
}
});
}
}.start();
}
public static final String KEY_121 = "http://website.com/scripts/application_query.php";
private String getServerData(String returnString) {
String UPC = getIntent().getStringExtra("UPCA");
InputStream is = null;
String result = "";
//the upc data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("UPCA",UPC));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(KEY_121);
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);
Log.e("log_tag", "Result ");
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
String UPCA = json_data.getString("UPCA");
String Product = json_data.getString("Product");
String Glute = json_data.getString("Gluten Free");
returnString += "\n\t" + jArray.getJSONObject(i);
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return returnString;
}
}

how to update listview in android after i add a new one

I'm doing something like contact app using a json
I can view a contact and add a new one but I can't make the contact update automatically
after I add a new one ( in my database already update ). I have to run my app again in eclipse to see a new contact
some of my main code is like this
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
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.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.*;
import android.content.*;
import android.database.Cursor;
import android.os.Bundle;
import android.view.*;
import android.widget.*;
public class MainActivity extends ListActivity {
private Cursor friendsCursor = null;
int position;
private ArrayList<Data> friends = null;
DateFormat fDateTimeDisplay = new SimpleDateFormat("dd-MM-yyyy");
DateFormat fDateTime = new SimpleDateFormat("yyyy-MM-dd");
public static String friendURL = "http://-----/friend.php";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
friends = new ArrayList<Data>();
setListAdapter(new DataAdapter());
try
{
JSONArray jArray = new JSONArray(getServerData());
String name, address, gender;
long code;
Date DOB;
friends.clear();
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
code = json_data.getLong("FriendCode");
name = json_data.getString("FriendName");
address = json_data.getString("FriendAddress");
gender = json_data.getString("FriendGender");
DOB = fDateTime.parse(json_data.getString("FriendDOB"));
Data data = new Data(name, address, gender, DOB,code);
friends.add(data); }
}catch(JSONException e){
//Display error message
Toast.makeText(this, "Error parsing data " + e.toString(), Toast.LENGTH_LONG).show();
}
catch (ParseException pe) {
Toast.makeText(this, "Error parsing data " + pe.toString(), Toast.LENGTH_LONG).show();
}
registerForContextMenu(getListView());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(this).inflate(R.menu.option, menu);
return(super.onCreateOptionsMenu(menu));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.add:
Intent intent = new Intent(this, AddActivity.class);
intent.putExtra("code", 1);
startActivityForResult(intent, 1);
return(true);
}
return(super.onOptionsItemSelected(item));
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK)
{
}
}
private String getServerData() {
InputStream is = null;
String result = "";
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(friendURL);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Toast.makeText(this, "Error in http connection " + e.toString(), Toast.LENGTH_LONG).show();
}
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){
Toast.makeText(this, "Error converting result " + e.toString(), Toast.LENGTH_LONG).show();
}
return result;
}
class DataAdapter extends ArrayAdapter<Data> {
DataAdapter() {
super(MainActivity.this, R.layout.row, friends);
}
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = getLayoutInflater();
row = inflater.inflate(R.layout.row, parent, false);
}
ViewHolder holder = (ViewHolder)row.getTag();
if (holder == null) {
holder = new ViewHolder(row);
row.setTag(holder);
}
holder.code.setText(Long.toString((friends.get(position).getcode())));
holder.txtName.setText(friends.get(position).getName());
holder.txtAddress.setText(friends.get(position).getAddress());
holder.txtGender.setText(friends.get(position).getGender());
holder.txtDOB.setText(fDateTimeDisplay.format(friends.get(position).getDOB()));
return(row);
}
}
}
and when i want to add a new contact I use Intent AddActivity to open a new layout call add
this is some code of my AddActivity
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.*;
import java.util.*;
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.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.*;
import android.os.Bundle;
import android.view.*;
import android.widget.*;
public class AddActivity extends Activity {
public static String friendInsertURL = "http://----/friendInsert.php";
Calendar calendar = Calendar.getInstance();
DateFormat fDateTime = new SimpleDateFormat("yyyy-MM-dd");
DateFormat fDateTimeDisplay = new SimpleDateFormat("dd-MM-yyyy");
long code;
EditText editName, editAddress;
RadioButton rbMale, rbFemale;
TextView txtDOBEdit;
String gender;
int position;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add);
editName = (EditText)findViewById(R.id.editName);
editAddress = (EditText)findViewById(R.id.editAddress);
txtDOBEdit = (TextView)findViewById(R.id.txtDOBEdit);
rbMale = (RadioButton)findViewById(R.id.rbMale);
rbFemale = (RadioButton)findViewById(R.id.rbFemale);
editName.setText("");
editAddress.setText("");
calendar = Calendar.getInstance();
txtDOBEdit.setText(fDateTimeDisplay.format(calendar.getTime()));
rbMale.setChecked(true);
}
private String setServerData(String mode, String name, String address, String gender, String dob) {
InputStream is = null;
String save = "";
ArrayList<NameValuePair> parameters = new ArrayList<NameValuePair>();
if (mode.equals("INSERT")) {
parameters.add(new BasicNameValuePair("FriendName", name));
parameters.add(new BasicNameValuePair("FriendAddress", address));
parameters.add(new BasicNameValuePair("FriendGender", gender));
parameters.add(new BasicNameValuePair("FriendDOB", dob));
friendInsertURL = "http://----/friendInsert.php";
}
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(friendInsertURL );
httppost.setEntity(new UrlEncodedFormEntity(parameters));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Toast.makeText(this, "Error in http connection " + e.toString(), Toast.LENGTH_LONG).show();
}
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();
save=sb.toString();
}catch(Exception e){
Toast.makeText(this, "Error converting result " + e.toString(), Toast.LENGTH_LONG).show();
}
return save;
}
public void chooseDate(View v) {
new DatePickerDialog(this, d,
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH))
.show();
}
DatePickerDialog.OnDateSetListener d = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, monthOfYear);
calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
TextView txtDOBEdit = (TextView)findViewById(R.id.txtDOBEdit);
txtDOBEdit.setText(fDateTimeDisplay.format(calendar.getTime()));
}
};
public void setSave(View view){
String save;
EditText editName = (EditText)findViewById(R.id.editName);
EditText editAddress = (EditText)findViewById(R.id.editAddress);
RadioButton rbMale = (RadioButton)findViewById(R.id.rbMale);
if (rbMale.isChecked()){
gender = "Male";}
else{
gender = "Female";
}
save = setServerData("INSERT", editName.getText().toString(), editAddress.getText().toString(), gender, fDateTime.format(calendar.getTime()));
finish();
}
}
I already search and found that I have to use adapter.notifyDataSetChanged() to update my adapter but when I put this code in my AddActivity
ArrayAdapter<Data> adapter = (ArrayAdapter<Data>)getListAdapter();
the getListAdapter error in there and I can't put a ListActivity, it cause my app error when I run it.
my problem is how to make my adapter update so I can always see my contact update wherever I add a new one ?
found something:
my code for add is add into database not the adapter .. is it because of that ? is it true then how to add into adapter ? is it in MainActivity or AddActivity ?
N.B.:
my listview is using viewholder to show the content..
really need help.. I already try all code that i know but still can't make it update except exit and run again the app
Changes needed in your code and paste it in your project
public class MainActivity extends ListActivity {
private ArrayList<Data> friends;
private ArrayAdapter adapter;
private ListViewlistview;
#Override
public void onCreate(Bundle savedInstanceState) {
friends = new ArrayList<Data>();
listview = (ListView) findViewById(R.id.listview_id);
adapter = new ArrayAdapter<Data>(this, R.id.list, friends);
listview.setAdapter(adapter);
}
This will update the listview, so you can call it after adding new one to a 'friends' list.
adapter.notifyDataSetChanged();

OutOfMemoryException when parsing large JSON responses

I am doing a project where I need to parse JSON from a URL through HttpClient. My code works fine for JSON object responses with a small amount of data. But when I use the same code to get a response with a huge amount of data (more than 3MB), I have a problem.
Here is my code:
JSONfunctions.java (function for json parsing)
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
//import java.util.HashMap;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.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.util.Log;
import android.widget.Toast;
#SuppressWarnings("unused")
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url){
InputStream is = null;
String result = "";
JSONObject jArray = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
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();
// Toast.makeText(getBaseContext, result, Toast.LENGTH_LONG).
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
try{
jArray = new JSONObject(result);
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return jArray;
}
}
ListJson.java
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
//import org.w3c.dom.Document;
//import org.w3c.dom.Element;
//import org.w3c.dom.NodeList;
import android.app.ListActivity;
import android.content.Intent;
//import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class ListJson extends ListActivity {
public static JSONObject json;
public static JSONArray data;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list1);
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
// String semail = "partha#excoflare.com";
// String spassword = "partha123";
// Toast.makeText(getApplicationContext(), JSONExample2.strEmail, Toast.LENGTH_LONG).show();
//Toast.makeText(getApplicationContext(), JSONExample2.strPwd, Toast.LENGTH_LONG).show();
//
json = JSONfunctions.getJSONfromURL("url here");
try{
data = json.getJSONArray("server_list");
for(int i=0;i<data.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = data.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("name", "" + e.getString("ServUser"));
map.put("email", "" + e.getString("ServURL"));
mylist.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
// try {
// JSONObject newObject=json.getJSONObject("subscription");
// JSONArray data1 = newObject.getJSONArray("cust_product");
//
// Toast.makeText(getApplicationContext(), data1.toString(), Toast.LENGTH_LONG).show();
//
// for(int i=0;i<data1.length();i++){
// HashMap<String, String> map1 = new HashMap<String, String>();
// JSONObject e = data.getJSONObject(i);
//
// map1.put("id", String.valueOf(i));
// map1.put("name", "" + e.getString("ServUser"));
// map1.put("email", "" + e.getString("ServURL"));
// mylist.add(map1);
// }
//
// } catch (JSONException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.item_list,
new String[] { "name", "email" },
new int[] { R.id.item_title, R.id.item_subtitle });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//#SuppressWarnings("unchecked")
//HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
// Toast.makeText(ListJson.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), parent.getItemAtPosition(position).toString(),
Toast.LENGTH_LONG).show();
// String a= parent.getItemAtPosition(position).toString();
Intent intent2= new Intent(ListJson.this, ListJson2.class);
startActivity(intent2);
}
});
}
I am getting an OutOfMemoryException. I changed heap_size to 192MB and ram size to 32MB, but with no luck. How can I fix this?
Big amounts of data of JSON must be cut to smaller pieces. For example you have a 50000 products on your database. Then it's wise to paginate API requests - get this huge amount of products by 100-500 records on one query. That will solve your problem.
This approach solves one problem more - errors caused by internet and gprs connection loss etc.
If API is yours then you can change this. If not, then this is a big failure of API design and you can send change request.
EDIT:
Did a little reading and found that highly recommended for parsing huge load of JSON data is http://jackson.codehaus.org/ (Jackson Processor). Haven't tried it, so cannot comment about this library. Also recommend you to save this JSON stream into the file (don't load it to memory) and then parse it by chunks.

Categories

Resources