App crashes on HttpResponse httpResponse = httpClient.execute(httpGet); - java

I working in android studio. I spent a lot of time searching how to retrive a specific row from mysql database but realy I cant do it every time my app crashed in HttpResponse httpResponse = httpClient.execute(httpGet);.
here is JSONParser class
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 mehtod
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();
int aa=sb.toString().indexOf("{");
int zz=sb.indexOf("{",aa+1);
String sss,zzz;
sss=sb.substring(932);
zzz=sb.substring(zz);
//json = sb.toString();
json=zzz.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);
/*JSONArray jsonArray=new JSONArray(json);
jObj=jsonArray.getJSONObject(0);*/
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
and this is activity
public class EditProductActivity extends Activity {
EditText txtName;
EditText txtPrice;
EditText txtDesc;
EditText txtCreatedAt;
Button btnSave;
Button btnDelete;
String pid;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// single product url
private static final String url_product_detials = "http://10.20.40.105/android_connect/get_product_details.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCT = "product";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_PRICE = "price";
private static final String TAG_DESCRIPTION = "description";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_product);
// getting product details from intent
Intent i = getIntent();
// getting product id (pid) from intent
pid = i.getStringExtra(TAG_PID);
// Getting complete product details in background thread
new GetProductDetails().execute();
});
}
/**
* Background Async Task to Get complete product details
* */
class GetProductDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EditProductActivity.this);
pDialog.setMessage("Loading product details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* 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
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 productObj = json
.getJSONArray(TAG_PRODUCT); // JSON Array
// get first product object from JSON Array
JSONObject product = productObj.getJSONObject(0);
// product with this pid found
// Edit Text
txtName = (EditText) findViewById(R.id.inputName);
txtPrice = (EditText) findViewById(R.id.inputPrice);
txtDesc = (EditText) findViewById(R.id.inputDesc);
// display product data in EditText
txtName.setText(product.getString(TAG_NAME));
txtPrice.setText(product.getString(TAG_PRICE));
txtDesc.setText(product.getString(TAG_DESCRIPTION));
}else{
// product with pid not found
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
pDialog.dismiss();
}
}
}
and in the last my php cod
<?php
/*
* Following code will get single product details
* A product is identified by product id (pid)
*/
// array for JSON response
$response = array();
$response["success"] = 0;
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for post data
if (isset($_GET["pid"])) {
$pid = $_GET['pid'];
// get a product from products table
$result = mysql_query("SELECT * FROM products WHERE pid like $pid");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$product = array();
$product["pid"] = $result["pid"];
$product["name"] = $result["name"];
$product["price"] = $result["price"];
$product["description"] = $result["description"];
$product["created_at"] = $result["created_at"];
$product["updated_at"] = $result["updated_at"];
// success
$response["success"] = 1;
// user node
$response["product"] = array();
array_push($response["product"], $product);
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>

Declare internet permission in your manifest:
<uses-permission android:name="android.permission.INTERNET" />

every time my app crashed in
HttpResponse httpResponse = httpClient.execute(httpGet);
Getting NetworkOnMainThreadException because HttpResponse.execute method is called on UI Thread using runOnUiThread in doInBackground.
No need to use runOnUiThread when using AsyncTask just return json.toString() from doInBackground :
protected String doInBackground(String... params) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("pid", pid));
JSONObject json = jsonParser.makeHttpRequest(
url_product_detials, "GET", params);
return json.toString();
}
and access UI from onPostExecute method for updating UI :
protected void onPostExecute(String result) {
super.onPostExecute(result);
JSONObject json =new JSONObject(result);
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// your code here...
}
}

Related

Java Android Studio

I am new to Android, I followed some tutorials online to create a login page with MySQL database hosted locally on my PC.
I am getting an error on JSONParser.java file says:
Error:(60, 61) error: incompatible types: List<Pair<String,String>> cannot be converted to List<? extends NameValuePair>
Here is the code in JSONParser.java
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 mehtod
public JSONObject makeHttpRequest(String url, String method,
List<Pair<String, String>> 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;
}
}
And here is for Login.java
public class login extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputUsername, inputPassword;
Button btnlogin;
TextView txtregister;
// url to login
private static String url_login = "http://10.0.2.2/VICOBA/login.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Edit Text
inputUsername = (EditText)findViewById(R.id.login_username);
inputPassword = (EditText)findViewById(R.id.login_password);
//Text View
txtregister = (TextView)findViewById(R.id.createAccount);
//Create button
btnlogin = (Button)findViewById(R.id.loginBtn);
btnlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Make login in background thread
String username = inputPassword.getText().toString();
String password = inputPassword.getText().toString();
new doLogin().execute(username,password);
}
});
}
/**
* Background Async Task to Create new product
* */
class doLogin extends AsyncTask<String, String, String>{
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(login.this);
pDialog.setMessage("Loading..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
//String description = inputDesc.getText().toString();
String username = args[0];
String password = args[1];
// Building parameters
List<Pair<String, String>> params = new ArrayList<>();
params.add(new Pair<>("username", username));
params.add(new Pair<>("password", password));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_login,
"POST", params);
// check log cat fro response
Log.d("Login", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), HomeActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
I have stacked here for some days trying searching for online solution with no success.

Android Json Parse returns nothing

I have a Json Parser Class which looks like this:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
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 {
JSONArray jObj = new JSONArray(json);
System.out.println(jObj.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Near the end at the last try and catch statement I print out the jsonObject as a string I correctly get the data in the console, the json looks like this:
[{"id":1,"name":"Blooper","description":"Blooper","video_url":"Blooper","platform":1100110011,"logo":"","avaible":0,"token":"","created_at":"2016-04-03
17:19:49","updated_at":"2016-04-03
17:19:49","release_at":"2016-05-08"},{"id":2,"name":"Blooper","description":"Blooper","video_url":"Blooper","platform":"11000000000","logo":"","avaible":0,"token":"","created_at":"2016-04-03
17:26:13","updated_at":"2016-04-03
17:26:13","release_at":"2016-05-08"}]
I used a validator and it is fine.
In my AllProducts activity I try to display that inside the android app.
It looks like this:
public class AllProductsActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://192.168.155.27:8000/index";
// JSON Node names
private static final String TAG_SUCCESS = "id";
private static final String TAG_PRODUCTS = "name";
private static final String TAG_PID = "description";
private static final String TAG_NAME = "video_url";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditProductActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllProductsActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllProductsActivity.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME},
new int[] { R.id.pid, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
If I try to print out this json:
JSONObject json = new JSONObject();
I get no values (null), so my view keeps being empty.
I get follwing error message:
java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.String org.json.JSONObject.toString()' on a null object
reference
at
com.example.androidhive.AllProductsActivity$LoadAllProducts$1.run(AllProductsActivity.java:150)
Line 150 is this :
Log.d("All Products: ", json.toString());
Thus Android Studio tells my that
jObj
here, in my jsonparser:
try {
JSONArray jObj = new JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
is never used.
http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/
I am not really experienced with this so I really hope for some help, thanks.
With JSONObject json = new JSONObject(); you are creating an empty JSONObject,
the JSONObject returned by jParser.makeHttpRequest(url_all_products, "GET", params); is never used.
You have to do it like this:
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
so your JSONObject from the JParser will be stored in json.

Android -php-mysql- JSON connection issue

I imported the androidhive project(http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/) and I added another table to the database. The details of the second table are displayed in the second listview. After clicking on listview item the edit page is displayed. But I didn't get the second table details in the corresponding edittexts.
Here are my java classes:
JSONParser.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
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;
}
}
2.JuicesActivity
public class JuicesActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> juicesList;
// url to get all products list
private static String url_all_juices = "http://10.0.2.2/android_connect/get_all_juices.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_JUICES = "juices";
private static final String TAG_JID = "j_id";
private static final String TAG_JUICENAME = "juice_name";
// products JSONArray
JSONArray juices = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_juices);
// Hashmap for ListView
juicesList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllJuices().execute();
// Get listview
ListView jv = getListView();
// on seleting single product
// launching Edit Product Screen
jv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String j_id = ((TextView) view.findViewById(R.id.jid)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),EditJuice.class);
// sending jid to next activity
in.putExtra(TAG_JID, j_id);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Editjuice Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllJuices extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(JuicesActivity.this);
pDialog.setMessage("Loading juices.. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_juices, "GET", params);
// Check your log cat for JSON response
Log.d("All Juices: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
juices = json.getJSONArray(TAG_JUICES);
// looping through All Products
for (int i = 0; i < juices.length(); i++) {
JSONObject c = juices.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_JID);
String name = c.getString(TAG_JUICENAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_JID, id);
map.put(TAG_JUICENAME, name);
// adding HashList to ArrayList
juicesList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
JuicesActivity.this, juicesList,
R.layout.list_juice, new String[] { TAG_JID,
TAG_JUICENAME},
new int[] { R.id.jid, R.id.jname });
// updating list view
setListAdapter(adapter);
}
});
}
}
}
3.EditJuice
public class EditJuice extends Activity {
EditText jName,jpric,jseller;
Button btnSavj,btnDeltJ;
String juid;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// single product url
private static final String url_juice_details= "http://10.0.2.2/android_connect/get_juice_details.php";
// url to update product
private static final String url_update_juice = "http://10.0.2.2/android_connect/update_juice.php";
// url to delete product
private static final String url_delete_juice = "http://10.0.2.2/android_connect/delete_juice.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_JUICES = "juices";
private static final String TAG_JID = "j_id";
private static final String TAG_JUICENAME = "juice_name";
private static final String TAG_JPRICE = "price";
private static final String TAG_SELLER = "seller";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.editjuice);
// save button
btnSavj = (Button) findViewById(R.id.btnSaveJ);
btnDeltJ = (Button) findViewById(R.id.btnDelJ);
// getting juice details from intent
Intent i = getIntent();
// getting juice id jid from intent
juid = i.getStringExtra(TAG_JID);
// Getting complete juice details in background thread
new Getjuice().execute();
// save button click event
btnSavj.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// starting background task to update product
new Savejuice().execute();
}
});
// Delete button click event
btnDeltJ.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// deleting product in background thread
new Deletejuice().execute();
}
});
}
/**
* Background Async Task to Get complete product details
* */
class Getjuice extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EditJuice.this);
pDialog.setMessage("Loading juice details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting juice 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
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("j_id", juid));
// getting juice details by making HTTP request
// Note that juice details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(url_juice_details, "GET", params);
// check your log for json response
Log.d("Single juice Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received juice details
JSONArray juiceObj = json.getJSONArray(TAG_JUICES); // JSON Array
// get first juice object from JSON Array
JSONObject juice = juiceObj.getJSONObject(0);
// juice with this jid found
// Edit Text
jName = (EditText) findViewById(R.id.EditNamej);
jpric = (EditText) findViewById(R.id.EditPricej);
jseller = (EditText) findViewById(R.id.Editseller);
// display product data in EditText
jName.setText(juice.getString(TAG_JUICENAME));
jpric.setText(juice.getString(TAG_JPRICE));
jseller.setText(juice.getString(TAG_SELLER));
}else{
// juice with jid not found
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
pDialog.dismiss();
}
}
/**
* Background Async Task to Save juice Details
* */
class Savejuice extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EditJuice.this);
pDialog.setMessage("Saving juice ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Saving juice
* */
protected String doInBackground(String... args) {
// getting updated data from EditTexts
String juice_name = jName.getText().toString();
String price = jpric.getText().toString();
String seller = jseller.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_JID, juid));
params.add(new BasicNameValuePair(TAG_JUICENAME, juice_name));
params.add(new BasicNameValuePair(TAG_JPRICE, price));
params.add(new BasicNameValuePair(TAG_SELLER, seller));
// sending modified data through http request
// Notice that update juice url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_update_juice,"POST", params);
// check json success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully updated
Intent i = getIntent();
// send result code 100 to notify about product update
setResult(100, i);
finish();
} else {
// failed to update juice
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once juice updated
pDialog.dismiss();
}
}
/*****************************************************************
* Background Async Task to Delete Product
* */
class Deletejuice extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EditJuice.this);
pDialog.setMessage("Deleting juice...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Deleting product
* */
protected String doInBackground(String... args) {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("j_id", juid));
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(url_delete_juice, "POST", params);
// check your log for json response
Log.d("Delete juice", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// product successfully deleted
// notify previous activity by sending code 100
Intent i = getIntent();
// send result code 100 to notify about product deletion
setResult(100, i);
finish();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
}
}
}
AddJuiceActivity
public class AddJuiceActivity extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputjName,inputPric,inputseller;
// url to create new product
private static String url_create_juice = "http://10.0.2.2/android_connect/create_juice.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_juice);
// Edit Text
inputjName=(EditText)findViewById(R.id.EditNam);
inputPric = (EditText) findViewById(R.id.EditPric);
inputseller = (EditText) findViewById(R.id.Editsell);
// Create button
Button btnj = (Button) findViewById(R.id.btnjuice);
// button click event
btnj.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewJ().execute();
}
});
}
/**
* Background Async Task to Create new product
* */
class CreateNewJ extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AddJuiceActivity.this);
pDialog.setMessage("Creating juice..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
String juicename = inputjName.getText().toString();
String price = inputPric.getText().toString();
String seller = inputseller.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("juice_name", juicename));
params.add(new BasicNameValuePair("price", price));
params.add(new BasicNameValuePair("seller", seller));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_juice,"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), JuicesActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
LogCat:
07-04 01:10:37.091: D/Single juice Details(891): {"success":1,"juice": [{"seller":"das","juice_name":"lemon","j_id":"9","price":"30.00"}]}
07-04 01:10:37.091: W/System.err(891): org.json.JSONException: No value for juices
07-04 01:10:37.101: W/System.err(891): at org.json.JSONObject.get(JSONObject.java:355)
07-04 01:10:37.101: W/System.err(891): at org.json.JSONObject.getJSONArray(JSONObject.java:549)
07-04 01:10:37.101: W/System.err(891): at com.example.androidhive.EditJuice$Getjuice$1.run(EditJuice.java:136)
07-04 01:10:37.101: W/System.err(891): at android.os.Handler.handleCallback(Handler.java:733)
07-04 01:10:37.141: W/System.err(891): at android.os.Handler.dispatchMessage(Handler.java:95)
07-04 01:10:37.181: W/System.err(891): at android.os.Looper.loop(Looper.java:136)
07-04 01:10:37.181: W/System.err(891): at android.app.ActivityThread.main(ActivityThread.java:5017)
07-04 01:10:37.181: W/System.err(891): at java.lang.reflect.Method.invokeNative(Native Method)
07-04 01:10:37.181: W/System.err(891): at java.lang.reflect.Method.invoke(Method.java:515)
07-04 01:10:37.191: W/System.err(891): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
07-04 01:10:37.251: W/System.err(891): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
07-04 01:10:37.251: W/System.err(891): at dalvik.system.NativeStart.main(Native Method)
Here is the php files.
get_all_juices.php
/*
* Following code will list all the juices
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// get all juices from juices table
$result = mysql_query("SELECT * FROM juices") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0)
{
// looping through all results
// juices node
$response["juices"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$juice = array();
$juice["j_id"] = $row["j_id"];
$juice["juice_name"] = $row["juice_name"];
$juice["price"] = $row["price"];
$juice["seller"] = $row["seller"];
// push single juice into final response array
array_push($response["juices"], $juice);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No juices found";
// echo no users JSON
echo json_encode($response);
}
?>
update_juice
<?php
/*
* Following code will update a juice information
* A juice is identified by juice id (j_id)
*/
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['j_id']) && isset($_POST['juice_name']) && isset($_POST['price'])
&& isset($_POST['seller']))
{
$j_id = $_POST['j_id'];
$juice_name = $_POST['juice_name'];
$price = $_POST['price'];
$seller = $_POST['seller'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql update row with matched j_id
$result = mysql_query("UPDATE juices SET juice_name = '$juice_name',
price = '$price', seller = '$seller' WHERE j_id = $j_id");
// check if row inserted or not
if ($result)
{
// successfully updated
$response["success"] = 1;
$response["message"] = "juice successfully updated.";
// echoing JSON response
echo json_encode($response);
} else {
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
get_juice_details
<?php
/*
* Following code will get single juice details
* A juice is identified by juice id (j_id)
*/
// 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
if (isset($_GET["j_id"]))
{
$j_id = $_GET['j_id'];
// get a juice from juices table
$result = mysql_query("SELECT *FROM juices WHERE j_id = $j_id");
if (!empty($result))
{
// check for empty result
if (mysql_num_rows($result) > 0)
{
$result = mysql_fetch_array($result);
$juice = array();
$juice["j_id"] = $result["j_id"];
$juice["juice_name"] = $result["juice_name"];
$juice["price"] = $result["price"];
$juice["seller"] = $result["seller"];
// success
$response["success"] = 1;
// user node
$response["juice"] = array();
array_push($response["juice"], $juice);
// echoing JSON response
echo json_encode($response);
} else {
// no juice found
$response["success"] = 0;
$response["message"] = "No juice found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no juice found
$response["success"] = 0;
$response["message"] = "No juice found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
Take out the runOnUiTread call from Getjuice doInBackground. Put the setText statements for the EditTexts in onPostExecute. Thats a start...

Receiving JSON java.lang.string cannot be converted to jsonarray

im making an app for a website. It has an JSON API. The URL im trying to fetch the result from is: http://api.bayfiles.net/v1/account/login/<user>/<password>
I get the error: java.lang.string cannot be converted to jsonarray when logging the error using logcat.
My main activity is:
public class MainActivity extends SherlockActivity {
EditText un,pw;
TextView error;
Button ok;
private ProgressDialog mDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
un = (EditText)findViewById(R.id.user);
pw = (EditText)findViewById(R.id.psw);
ok = (Button)findViewById(R.id.button1);
error = (TextView)findViewById(R.id.textView1);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//error.setText("Clicked");
//Intent startNewActivityOpen = new Intent(LoginActivity.this, FilesActivity.class);
//startActivityForResult(startNewActivityOpen, 0);
JsonAsync asyncTask = new JsonAsync();
// Using an anonymous interface to listen for objects when task
// completes.
asyncTask.setJsonListener(new JsonListener() {
public void onObjectReturn(JSONObject object) {
handleJsonObject(object);
}
});
// Show progress loader while accessing network, and start async task.
//mDialog = ProgressDialog.show(this, getSupportActionBar().getTitle(),
// getString(R.string.loading), true);
asyncTask.execute("http://api.bayfiles.net/v1/account/login/spxc/mess2005");
}
});
}
private void handleJsonObject(JSONObject object) {
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
try {
JSONArray shows = object.getJSONArray("error");
for (int i = 0; i < shows.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = shows.getJSONObject(i);
//map.put("video_id", String.valueOf(i));
map.put("session", "" + e.getString("session"));
mylist.add(map);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data: " + e.toString());
}
error.setText("session");
/*
//Intent myIntent = new Intent(ListMoviesController.this,
// TestVideoController.class);
myIntent.putExtra("video_title", o.get("video_title"));
myIntent.putExtra("video_channel", o.get("video_channel"));
myIntent.putExtra("video_location", o.get("video_location"));
startActivity(myIntent); */
}{
if (mDialog != null && mDialog.isShowing()) {
mDialog.dismiss();
}
}
}
And this is my adapter: JSONfunctions.java
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);
try {
// Add your data
/*List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("key", "stianxxs"));
nameValuePairs.add(new BasicNameValuePair("secret", "mhfgpammv9f94ddayh8GSweji"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); */
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
//HttpResponse response = httpclient.execute(httppost);
HttpEntity httpEntity = response.getEntity();
is = httpEntity.getContent();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}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;
}
}
Why im i getting this error? When using the right username and password in the url you would get: {"error":"","session":"RANDOM NUMBER"}
And as you can see i try to fetch this number. Any help is much appreciated!
You are getting this error because in line
JSONArray shows = object.getJSONArray("error");
you are trying to get value for key error and treat is as an array, whereas it's not - it's an empty string. Therefore you need to get it as a string:
String error = object.getString("error");
Similarly, if you need to get your "session", you can get it with
String session = object.getString("session");
P.S. Note that this is assuming that your JSONObject object actually contains the object represented by the string in your question.

json-parsing errors at run time

I am trying to send some sign up information to a php server from my Android app.
I have two classes: RegisterActivity and JSONParser.
While I'm trying to run this programs there is some errors like this:
Error parsing data org.json.JSONException: Value not of type java.lang.String cannot be converted to JSONObject" and "android.os.AsyncTask$3.done(AsyncTask.java:299)
Here is my code:
RegisterActivity.java
public class RegisterActivity extends Activity {
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText username;
EditText email;
EditText password;
EditText RePass;
private static String url_create_product = "http://oranz.co/pmdtest/index.php";
private static final String TAG_SUCCESS = "sucess";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set View to register.xml
setContentView(R.layout.register);
Button registerscreen=(Button)findViewById(R.id.btnCntnueRegister);
// Listening to Login Screen link
email = (EditText)findViewById(R.id.reg_email);
password =(EditText)findViewById(R.id.reg_password);
username =(EditText)findViewById(R.id.reg_username);
RePass = (EditText)findViewById(R.id.rereg_password);
EditText passwords=(EditText)findViewById(R.id.reg_password);
passwords.setTransformationMethod(new PasswordTransformationMethod());
EditText repasswords = (EditText) findViewById(R.id.rereg_password);
repasswords.setTransformationMethod(new PasswordTransformationMethod());
registerscreen.setOnClickListener(new View.OnClickListener(){
public void onClick(View arg0) {
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
if(email.getText().toString().equals("")&&password.getText().toString().equals("")&&username.getText().toString().equals("")&&RePass.getText().toString().equals(""))
{
Toast toast = Toast.makeText(context, "Please Enter a valed data. !", duration);
toast.show();
}
else if(email.getText().toString().equals("")||password.getText().toString().equals("")||username.getText().toString().equals("")||RePass.getText().toString().equals(""))
{
Toast toast = Toast.makeText(context, "Please check any field is blank. !", duration);
toast.show();
}
else if(password.getText().toString().compareTo(RePass.getText().toString())==0)
{
Intent k = new Intent(getApplicationContext(), ContinueRegister.class);
startActivity(k);
new CreateNewUser().execute();
}
else
{
Toast toast = Toast.makeText(context, "Password matching is failed. !", duration);
toast.show();
}
}
});
TextView loginScreen = (TextView) findViewById(R.id.link_to_login);
loginScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent m = new Intent(getApplicationContext(),LoginActivity.class);
startActivity(m);
}
});
}
class CreateNewUser extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(RegisterActivity.this);
pDialog.setMessage("Creating Product..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
String Username = username.getText().toString();
String Email = email.getText().toString();
String Password = password.getText().toString();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Username", Username));
params.add(new BasicNameValuePair("Email", Email));
params.add(new BasicNameValuePair("Password",Password));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created user
Intent i = new Intent(getApplicationContext(),FinishSignupActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create user
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
 * After completing background task Dismiss the progress dialog
 * **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
JSONParser.java:
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;
}
}
This is due to the android emulator crash there is no mistakes in the programs.

Categories

Resources