Taking data parsed with JSON and displaying it as text in Android - 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;
}
}

Related

Display image from mysql database [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
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();
}
}
}
You can refer the following link http://sunil-android.blogspot.in/2013/10/insert-and-retrieve-image-into-db.html. It will helpfull to you.

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

passing json data to a custom object - android

I'm having trouble with my application. I'm trying to pass json data from my database in a custom class in android, and then display this in a list. When i run my app nothing happens, no errors, no list displayed. if anyone can help i would be very grateful!! :)
All the network stuff is done in async, and im trying to return the an array of objects so i suspect that this could be the problem is here or else when i am converting the string from the httphandler class into a JSONArray.
this is my main activity
package com.example.test1;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class clubpage extends Activity {
class Programme {
public String name;
public String event;
public String price;
}
String clubphp = "http://10.0.2.2/corkgaa/Nemo.php";
String progString;
ArrayList<Programme> Programmedata = new ArrayList<Programme>();
ListView clublistview = (ListView)findViewById(R.id.listview1);
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.clubpage);
new Dbhandler().execute(clubphp);
ArrayAdapter<Programme> adapter = new ArrayAdapter<Programme>(this,
android.R.layout.simple_list_item_1, Programmedata);
clublistview.setAdapter(adapter);
}
public class Dbhandler extends AsyncTask<String, Void, ArrayList<Programme>> {
protected ArrayList<Programme> doInBackground(String... arg0) {
ArrayList<Programme> arraydata = new ArrayList<Programme>();
progString = httphandler.HttpGetExec(clubphp);
try{
JSONArray jArray = new JSONArray(progString);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
Programme Progresult = new Programme();
Progresult.name = json_data.getString("Name");
Progresult.event = json_data.getString("Event");
Progresult.price = json_data.getString("Price");
arraydata.add(Progresult);
}
}
catch(JSONException e1){
}
catch (ParseException e1) {
e1.printStackTrace();
}
return arraydata;
}
#Override
protected void onPostExecute(ArrayList<Programme> result) {
Programmedata = result;
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
}
httphandler class here:
package com.example.test1;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
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 android.util.Log;
public class httphandler {
//Main Dev setup
public static String HttpGetExec (String URI) {
// TODO Auto-generated method stub
String result = "no response";
InputStream is = null;
StringBuilder sb = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/corkgaa/Nemo.php");
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);
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){
Log.e("log_tag", "Error converting result "+e.toString());
}
return result;
//aa=new ArrayAdapter<String>(clubpage.this, R.layout.listrow, R.id.title, result);
//ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.listrow, R.id.title, result);
//listview.setAdapter(aa);
}
}
Move this line to your onCreate after setContentView
clublistview = (ListView)findViewById(R.id.listview1);
And move the following lines to onPostExecute in your async task:
ArrayAdapter<Programme> adapter = new ArrayAdapter<Programme>(this,
android.R.layout.simple_list_item_1, Programmedata);
clublistview.setAdapter(adapter);
While your async task is executing, consider showing some kind of progress indicator.

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

android text not visible

I am sending some information from my application to server and waiting for the response. Before i send i set my textview for message to display "processing request" and after getting response i display a different message.
This processing message is not getting displayed. Is it beacuse the UI is getting blocked due to other operation.
How to handle this. Threading is not giving correct result as need to display the response.
SO that involve UI in the thread .
package com.PandG.app.android.activities;
import java.io.BufferedReader;
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.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.apache.http.params.HttpConnectionParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.PandG.app.android.R;
import com.PandG.app.android.dataAccess.SettingsDBAccess;
import com.PandG.app.android.entity.Job;
import com.PandG.app.android.entity.Settings;
import com.PandG.app.android.services.JobsManager;
import com.lib.android.Utils.Utils;
import com.lib.android.activity.BaseActivity;
import com.lib.android.dataAccess.DatabaseManager;
public class JobCheckoutActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setViewContent();
}
private void setViewContent() {
Settings setting = getSettings();
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.job_checkout);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.customtitle);
//new DataProcess().execute(null);
TextView text1 = (TextView)findViewById(R.id.checkoutmessage);
text1.setText("Processiong Job Cart ...");
if(setting!=null){
TextView text2 = (TextView)findViewById(R.id.checkoutheading);
text2.setVisibility(View.GONE);
Button homeButton = (Button)findViewById(R.id.gohome);
homeButton.setVisibility(View.GONE);
JSONObject jobObject =encodeData(setting);
sendDataToServer(jobObject);
}
}
private void sendDataToServer(JSONObject jobObject) {
TextView text1 = (TextView)findViewById(R.id.checkoutmessage);
text1.setText("Processiong Job Cart ...");
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout
// Limit
HttpResponse response;
try {
HttpPost post = new HttpPost(Utils.getPostUrl());
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("orderparameters",
jobObject.toString()));
Log.i("Job ORDER", jobObject.toString());
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = client.execute(post);
checkResponseFromServer(response);
ClearCart();
} catch (Exception e) {
Log.w("error", "connection failed");
Toast.makeText(this, "Order not placed due to connection error",
Toast.LENGTH_LONG);
e.printStackTrace();
}
}
private void ClearCart() {
JobsManager.JobsCartList.clear();
}
private void checkResponseFromServer(HttpResponse response) {
try {
if (response != null) {
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
String line;
StringBuffer buffer = new StringBuffer();
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
in.close();
JSONObject jsonResponse = new JSONObject(buffer.toString());
Log.i("Status", jsonResponse.getString("status"));
Log.i("Status", jsonResponse.getString("message"));
Log.i("Status", jsonResponse.getString("debug"));
TextView text1 = (TextView)findViewById(R.id.checkoutheading);
text1.setVisibility(View.VISIBLE);
TextView text = (TextView) findViewById(R.id.checkoutmessage);
if (jsonResponse.getString("status").equals("SUCC")) {
text.setText( Html.fromHtml(getString(R.string.checkout_body1)));
} else
text.setText(jsonResponse.getString("message")
+ jsonResponse.getString("debug"));
}
} catch (Exception ex) {
}
}
private JSONObject encodeData(Settings setting) {
JSONObject jobObject = new JSONObject();
try {
JSONObject jobject = new JSONObject();
jobject.put("name", setting.getName());
jobject.put("email", setting.getEmail());
jobject.put("phone", setting.getPhone());
jobject.put("school", setting.getSchool());
jobject.put("major", setting.getMajor());
jobObject.put("customer", jobject);
JSONArray jobsarray = new JSONArray();
for (Job job : JobsManager.JobsCartList) {
JSONObject jobEntry = new JSONObject();
jobEntry.put("jobtitle",job.getTitle());
jobEntry.put("qty","1");
jobsarray.put(jobEntry);
}
jobObject.put("orders", jobsarray);
} catch (JSONException ex) {
}
return jobObject;
}
private Settings getSettings() {
SettingsDBAccess settingsDBAccess = new SettingsDBAccess(
DatabaseManager.getInstance());
Settings setting = settingsDBAccess.getSetting();
if (setting==null){
startActivityForResult((new Intent(this,SettingsActivity.class)),Utils
.getDefaultRequestCode());
}
return setting;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Settings setting = new SettingsDBAccess(
DatabaseManager.getInstance()).getSetting();
if(setting!=null){
JSONObject jobObject = encodeData(setting);
sendDataToServer(jobObject);
}
}
/* private class DataProcess extends AsyncTask {
#Override
protected void onPostExecute(Object result) {
}
#Override
protected Object doInBackground(Object... arg0) {
processDataandsend();
return null;
}
private void processDataandsend() {
Settings setting = getSettings();
if(setting!=null){
TextView text2 = (TextView)findViewById(R.id.checkoutheading);
text2.setVisibility(View.GONE);
Button homeButton = (Button)findViewById(R.id.gohome);
homeButton.setVisibility(View.GONE);
JSONObject jobObject =encodeData(setting);
sendDataToServer(jobObject);
}
}
} */
}
You should not perform HTTP-work on the UI-thread. Instead use AsyncTask
In your AsyncTask you are only allowed to update the UI in two places:
#Override
protected void onPreExecute()
TextView.setText("Beginning HTTP-work..Please wait");
{
and
#Override
protected void onPostExecute(Void v) {
TextView.setText("Done..SUCCESS!");
}
Use these two to update the UI before and after the HTTP-work has been done.
Long operations must be in background. Best way to implement this on Android, use AsyncTask, for more information: http://developer.android.com/reference/android/os/AsyncTask.html

Categories

Resources