Updating JSONFile Hosted on Web Server - android

This is my code for getting the JSON file in web:
package com.example.maclocation;
import java.io.IOException;
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.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.Toast;
public class MainActivity extends Activity {
String[] n1;
String[] n2;
String[] n3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new ActorsAsyncTask().execute("link here");
}
class ActorsAsyncTask extends AsyncTask<String, Void, Boolean> {
This is my code for getting the JSON file in web:
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpPost post = new HttpPost(urls[0]);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(post);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.optJSONArray("coordinates");
n1 = new String[jarray.length()];
n2 = new String[jarray.length()];
n3 = new String[jarray.length()];
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
n1[i] = object.getString("place").toString();
n2[i] = object.getString("lat").toString();
n3[i] = object.getString("lng").toString();
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
This is my code for getting the JSON file in web:
protected void onPostExecute(Boolean result) {
if(result == false){
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}else{
for (int i = 0; i < n1.length; i++) {
// String xss= actorsList.
Toast.makeText(getApplicationContext(), n1[i] + "*" + n2[i]+ "*" +n3[i] , Toast.LENGTH_LONG).show();
}
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Question:
Is it possible to update the JSON file that is hosted in web server? Like updating my current location? I am using ADT Eclipse.

So, you need to code it on the server side, using probably php, ruby, python, or any other language you may be using on the server..
And then through the app you can make an http request passing some parameter to identify which action you are taking on the same server where the JSON file is hosted (so you can reach it) and then you can edit it!
This tutorial is very good: http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/
In this case it is a database, not an JSON file, but the idea is the same.

Related

How To Create AppWidget to display JSON Parse Images and Text

I'm New to android development and I don't understand clearly how to create a appwidget for application that parse JSON Data and display in list.
I solved my problem using this link (https://laaptu.wordpress.com/2013/07/19/android-app-widget-with-listview/).
It has Series of Tutorials
(1.app widget with listview
2.populate app widget listview with data from web
3.download images and show on imageview of appwidget with listview
4.setting update interval on appwidget with listview
5.how to make appwidget update work after phone reboot)
To Use Simple JSON URL to fetch images and texts, i made the following changes in RemoteFetchService.java from third tutorial,
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.IBinder;
import android.util.Log;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.example.mk.widgets.data.DatabaseManager;
import com.example.mk.widgets.data.FileManager;
public class RemoteFetchService extends Service {
private int appWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
JSONObject jsonobject;
JSONArray jsonarray;
AQuery aquery;
private String remoteJsonUrl = "http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors";
public static ArrayList<ListItem> listItemList;
private int count = 0;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
/*
* Retrieve appwidget id from intent it is needed to update widget later
* initialize our AQuery class
*/
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID))
appWidgetId = intent.getIntExtra(
AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
aquery = new AQuery(getBaseContext());
new DownloadJSON().execute();
return super.onStartCommand(intent, flags, startId);
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// Create an array
listItemList = new ArrayList<ListItem>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions.getJSONfromURL(remoteJsonUrl);
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("actors");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
ListItem listItem = new ListItem();
listItem.heading = jsonobject.getString("name");
listItem.content = jsonobject.getString("country");
listItem.imageUrl = jsonobject.getString("image");
listItemList.add(listItem);
}
storeListItem();
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
}
/**
* Instead of using static ArrayList as we have used before,no we rely upon
* data stored on database so saving the fetched json file content into
* database and at same time downloading the image from web as well
*/
private void storeListItem() {
DatabaseManager dbManager = DatabaseManager.INSTANCE;
dbManager.init(getBaseContext());
dbManager.storeListItems(appWidgetId, listItemList);
int length = listItemList.size();
for (int i = 0; i < length; i++) {
ListItem listItem = listItemList.get(i);
final int index = i;
aquery.ajax(listItem.imageUrl, Bitmap.class,new AjaxCallback<Bitmap>() {
#Override
public void callback(String url, Bitmap bitmap, AjaxStatus status) {
super.callback(url, bitmap, status);
storeBitmap(index, bitmap);
};
});
}
}
/**
* Saving the downloaded images into file and after all the download of
* images be complete begin to populate widget as done previously
*/
private void storeBitmap(int index, Bitmap bitmap) {
FileManager.INSTANCE.storeBitmap(appWidgetId, bitmap,
listItemList.get(index).heading, getBaseContext());
count++;
Log.i("count",String.valueOf(count) + "::"+ Integer.toString(listItemList.size()));
if (count == listItemList.size()) {
count = 0;
populateWidget();
}
}
/**
* Method which sends broadcast to WidgetProvider so that widget is notified
* to do necessary action and here action == WidgetProvider.DATA_FETCHED
*/
private void populateWidget() {
Intent widgetUpdateIntent = new Intent();
widgetUpdateIntent.setAction(WidgetProvider.DATA_FETCHED);
widgetUpdateIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
appWidgetId);
sendBroadcast(widgetUpdateIntent);
this.stopSelf();
}
}
JSONfunctions.java
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 org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// Download JSON data from URL
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();
} 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;
}
}
Hope this helps someone and Great thanks to ( https://stackoverflow.com/users/739306/laaptu ) for the tutorials.

Android App JSON Parsing

I am trying to parse JSON that I am receiving from a URL linked in my android application. I want to output this data to TextViews in my application. Source code below.
Right now this is how the JSON is displayed on the app
[
{
"IndividualID": 1,
"FullName": "Sean Kelly",
"DOB": "07/06/1987",
"MedicalHistory": "Ulcerative Colitis",
"Medication": "Asacolon",
"Alergies": "Penicillin"
}
]
Fragment2.java (commented out part is where I tried parsing but nothing is displayed)
package ie.itsligo.medication;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class Fragment2 extends Fragment {
TextView txtId;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment2_layout, container, false);
new LongRunningGetIO().execute();
return view;
}
private class LongRunningGetIO extends AsyncTask <Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n>0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n>0) out.append(new String(b, 0, n));
}
return out.toString();
}
#Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("https://api.myjson.com/bins/363s3");
String text = null;
try {
HttpResponse response = httpClient.execute(httpGet, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
return text;
}
protected void onPostExecute(String results) {
if (results!=null) {
txtId = (TextView) getView().findViewById(R.id.txtId);
txtId.setText(results);
/*JSONObject jObj;
try {
jObj = new JSONObject();
JSONArray jArr = jObj.getJSONArray(results);
for (int i=0; i < jArr.length(); i++){
JSONObject obj = jArr.getJSONObject(i);
String fullname = obj.getString("FullName");
txtId = (TextView) getView().findViewById(R.id.txtId);
txtId.setText(fullname+"");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
}
}
}
You can use the JSONArray and JSONObject classes available in the Android SDK. After you load your JSON string,you can parse it as:
JSONArray myJSONArray=new JSONArray(jsonString);
//jsonString contains your JSON loaded
//from the Internet probably.
for(int i=0;i<myJSONArray.length();i++){
JSONObject obj=(JSONObject) myJSONArray.get(i);
//Now you can access your data here.
String individualID=obj.getString("IndividualID");//get value by key
String fullName=obj.getString("FullName");
//.... similarly get other values and assign them to your views accordingly.
}
I hope this helps.
You can use GSON library for JSON parsing in Android. You can parse this JSON in this way:
List<YourObject> listOfYourObject = new Gson().fromJson(results, new TypeToken<List<YourObject>>() {}.getType());
In the YourObject define the fields exactly how they are on the response or you can use #SerializedName annotation and name your fields how you want.

Trouble in getting data from webserver

I wrote this code to read and write data from webserver (mysql databse) and then all the data will be show on my andriod application.
In this regard I used PHP services for reading and writing the data from web server. Everything is working fine it gets data from web server correctly but when it reaches at this line:
int success = jsonObject.getInt(TAG_SUCCESS);
It shows a null pointer exception I don't know why but it actually made me insane.
Code:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.commons.collections.*;
//import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import org.json.*;
public class MiddleActivity extends Activity {
Button btnMiddleDB;
ProgressDialog pDialog ;
JSONParser jsonParser = new JSONParser();
JSONArray places = null;
private static final String URL = "http://192.168.1.2/android_connect/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
ArrayList<HashMap<String, String>> placesList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_middle);
new LoadGettingFromDatabase().execute();
btnMiddleDB = (Button) findViewById(R.id.button1);
btnMiddleDB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
}
});
}
running background thread for getting data from webserver
class LoadGettingFromDatabase extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MiddleActivity.this);
pDialog.setMessage("Getting from database...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
**after getting data from webserver parse it to json and store it into string**
#Override
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
Log.d("Seen","seen1");
JSONObject jsonObject = jsonParser.makeHttpRequest(URL, "GET" ,params);
Log.d("String","JSON 2");
//Log.d("All entries","Entries" + jsonObject.toString());
try{
Log.d("Seen","seen2");
ACTUALLY THE PROBLEM IS HERE
int success = jsonObject.getInt(TAG_SUCCESS);
Log.d("Seen","seen5");
if(success == 1){
//Entries found
Log.d("Seen","seen6");
places = jsonObject.getJSONArray(TAG_PRODUCTS);
for(int i=0;i<places.length();i++){
JSONObject temp = places.getJSONObject(i);
String id = temp.getString(TAG_PID);
String name = temp.getString(TAG_NAME);
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put(TAG_PID, id);
hashMap.put(TAG_NAME, name);
placesList.add(hashMap);
}
}
} catch (Exception e) {
Log.e("success","success status " + e);
}
return null;
}
public void onProExecute(String file_url){
pDialog.dismiss();
runOnUiThread(new Runnable(){
public void run(){
ListAdapter listAdapter = new SimpleAdapter(MiddleActivity.this, placesList, R.layout.list_item, new String[]{
TAG_PID, TAG_NAME},new int[]{R.id.ID, R.id.Name});
ListView listView = (ListView) findViewById(R.layout.list_item);
listView.setAdapter(listAdapter);
};
});
};
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_middle, menu);
return true;
}
}
**and log cat is**
05-07 00:29:54.419: D/Seen(30282): seen1
05-07 00:29:54.569: D/Seen(30282): seen3
05-07 00:29:54.909: D/Seen(30282): seen4
05-07 00:29:54.979: D/String(30282): JSON get_all_products.php
05-07 00:29:54.979: D/String(30282): db_connect.php
05-07 00:29:54.979: D/String(30282): db_config.php
05-07 00:29:54.979: D/String(30282): {"success":0,"message":"No products found
05-07 00:29:55.300: D/String(30282): JSON 1
05-07 00:29:55.300: D/String(30282): JSON 2
05-07 00:29:55.310: D/Seen(30282): seen2
**05-07 00:29:55.310: E/success(30282): success status
java.lang.NullPointerException**
and here is my jsonparser class
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Your jsonObject is null, debug the app by setting breakpoint at line->
JSONObject jsonObject = jsonParser.makeHttpRequest(URL, "GET" ,params);
And check value of jsonObject.

How to display a JSON from web service in Android List

I am trying since yesterday to make my application take some JSON data generated by a PHP file and then display this data in a list view.
The PHP File is encoding data using encode method:
echo json_encode($results);
Viewed from the browsers view source the JSON generated by file.php looks like this:
["","CSD1939","CSD1939"]
The JSONLint (A great tool) validates this as a correct JSON format.
When I am trying to use my application to fetch this JSON from the webservice I am fetching it as a String first but I am having trouble passing it to the adapter and making it display correctly.
I only managed until now to create a listview that displays a String Array.
What is the best way to fetch this JSON data and display it in the list.
package com.example.ams;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import 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.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class ViewClasses extends Activity {
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_classes);
new GetInfo().execute();
// ==============Functionality Start====================
// final ListView listview = (ListView) findViewById(R.id.listview);
}
private class GetInfo extends AsyncTask<Void, Void, String> {
protected String doInBackground(Void... params) {
// Fetch the JSON from the web and we pass it as a string to
// the ON POST EXECUTE method
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(
"file.php?get=XXX");
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(this.toString(), "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}
protected void onPostExecute(String result) {
// Here it should turn it into a JSON and then display it in a list.
// Gets the list view
final ListView listview = (ListView) findViewById(R.id.listview);
// Converts the String to a JSON array
System.out.println(result);
JSONArray jsonArray;
try {
System.out.println(result);
jsonArray = new JSONArray(result);
Log.i(ViewClasses.class.getName(), "Number of entries "
+ jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Log.i(ViewClasses.class.getName(),
jsonObject.getString("text"));
// Converts JSON array to Java Array
final ArrayList<String> list = new ArrayList<String>();
// values instead of jsonArray
if (jsonArray != null) {
int len = jsonArray.length();
for (int i1 = 0; i1 < len; i1++) {
list.add(jsonArray.get(i).toString());
}
}
final StableArrayAdapter adapter = new StableArrayAdapter(
getApplicationContext(),
android.R.layout.simple_list_item_1, list);
listview.setAdapter(adapter);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class StableArrayAdapter extends ArrayAdapter<String> {
HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();
public StableArrayAdapter(Context context, int textViewResourceId,
List<String> objects) {
super(context, textViewResourceId, objects);
for (int i = 0; i < objects.size(); ++i) {
mIdMap.put(objects.get(i), i);
}
}
#Override
public long getItemId(int position) {
String item = getItem(position);
return mIdMap.get(item);
}
#Override
public boolean hasStableIds() {
return true;
}
}
}
My Layout XML file looks like this
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Running this code I am getting a blank screen.
Any help, pointers, hints would be greatly appreciated
It is just returning JSONArray with Strings, so you should not create JSONObject from it.
JSONObject jsonObject = jsonArray.getJSONObject(i);
this will cause Exception as JSONArray doesn't contain JSONObjects.
So parse like this
ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < jsonArray.length(); i++) {
list.add(jsonArray.get(i).toString());
}

Connecting android to mysql database... application ends

When I try to connect my app to MySQL database the application abruptly stops. I think the problem is with the jasonparsor class which I wrote. I need to accept the filed without posting any thing. how should I change my classes..
my JasonParsor is given below
package com.mahavega.qcdemo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
my activity which I want to display the data is
package com.mahavega.qcdemo;
import java.util.ArrayList;
import java.util.List;
import com.mahavega.qcdemo.R;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends Activity implements OnClickListener {
JSONParser jsonParser = new JSONParser();
private static final String url_product_detials = "http://neogdgt.com/mob/get_det.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_EVENT = "event";
private static final String TAG_EVENTITLE = "event_title";
private static final String TAG_EVENTDET = "event_details";
private GestureDetector gestureDetector;
View.OnTouchListener gestureListener;
// Condetect cd = new Condetect(getApplicationContext());
// Boolean isInternetPresent = cd.isConnectingToInternet();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gestureDetector = new GestureDetector(this, new MyGestureDetector());
gestureListener = new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
};
new GetEventDetails().execute();
ImageView ad = (ImageView) findViewById(R.id.imageView1);
ImageView im2 = (ImageView) findViewById(R.id.imageView2);
ImageView im3 = (ImageView) findViewById(R.id.imageView3);
ImageView im4 = (ImageView) findViewById(R.id.imageView4);
ImageView im5 = (ImageView) findViewById(R.id.imageView5);
ad.setOnClickListener(MainActivity.this);
im2.setOnTouchListener(gestureListener);
im2.setOnClickListener(MainActivity.this);
im3.setOnTouchListener(gestureListener);
im3.setOnClickListener(MainActivity.this);
im4.setOnTouchListener(gestureListener);
im4.setOnClickListener(MainActivity.this);
im5.setOnTouchListener(gestureListener);
im5.setOnClickListener(MainActivity.this);
ad.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
boolean inet = isOnline();
if (inet)
{
startActivity(new Intent(MainActivity.this, Adds.class));
overridePendingTransition(R.anim.slide_left, R.anim.slide_right);
finish();
}
else {
displayAlert();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
class MyGestureDetector extends SimpleOnGestureListener {
#Override
public boolean onFling (MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
{
float sensitvity = 50;
if((e1.getX() - e2.getX()) < sensitvity){
startActivity(new Intent(MainActivity.this, Login.class));
overridePendingTransition(R.anim.slide_right, R.anim.slide_left);
finish();
}
else if((e2.getX() - e1.getX()) > sensitvity){
startActivity(new Intent(MainActivity.this, Login.class));
overridePendingTransition(R.anim.slide_right, R.anim.slide_left);
finish(); }
return super.onFling(e1, e2, velocityX, velocityY);
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
#Override
public void onBackPressed() {
finish();
super.onBackPressed();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ( keyCode == KeyEvent.KEYCODE_BACK
&& event.getRepeatCount() == 0) {
onBackPressed();
}
return true;
}
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
public void displayAlert()
{
new AlertDialog.Builder(this).setMessage("Please Check Your Internet Connection and Try Again")
.setTitle("Network Error")
.setCancelable(true)
.setNeutralButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){
}
})
.show();
}
class GetEventDetails extends AsyncTask<String, String, String> {
/**
* Getting product details in background thread
* */
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// Check for success tag
int success;
try {
// Building Parameters
String pid="1";
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("pid", pid));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_product_detials, "GET", params);
// check your log for json response
Log.d("Single Product Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray eventObj = json
.getJSONArray(TAG_EVENT); // JSON Array
// get first product object from JSON Array
JSONObject event = eventObj.getJSONObject(0);
// product with this pid found
TextView txtEventname=(TextView) findViewById(R.id.textView2);
TextView txtEventdet=(TextView) findViewById(R.id.textView3);
// Edit Text
txtEventname.setText(event.getString(TAG_EVENTITLE));
txtEventdet.setText(event.getString(TAG_EVENTDET));
}else{
// product with pid not found
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
}
}
and my getdetails.php class is
<?php
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for post data
// get a product from products table
$result = mysql_query("SELECT *FROM tb_event_details WHERE event_id=1");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$events = array();
$events["event_id"] = $result["event_id"];
$events["event_title"] = $result["event_title"];
$events["event_details"] = $result["event_details"];
// success
$response["success"] = 1;
// user node
$response["events"] = array();
array_push($response["events"], $events);
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No event found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No event found";
// echo no users JSON
echo json_encode($response);
}
?>
just add
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads().detectDiskWrites().detectNetwork()

Categories

Resources