I am parsing this JSON data from Rotten Tomatoes website. I am just trying to get the genres array and put it in a toast. But no toast is coming. Here is my code:
public class MovieInfo extends Activity
{
private static final String API_KEY = "xxxxxxxxxxxxxxxxxxxxxxx";
String[] Genres;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.movieinfo);
String MovieID = getIntent().getExtras().getString("MovieID");
new RequestTask().execute("http://api.rottentomatoes.com/api/public/v1.0/movies/"+MovieID+".json?apikey=" + API_KEY);
}
private class RequestTask extends AsyncTask<String, String, String>
{
// make a request to the specified url
#Override
protected String doInBackground(String... uri)
{
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try
{
// make a HTTP request
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK)
{
// request successful - read the response and close the connection
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
}
else
{
// request failed - close the connection
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
}
catch (Exception e)
{
Log.d("Test", "Couldn't make a successful request!");
}
return responseString;
}
#Override
protected void onPostExecute(String response)
{
super.onPostExecute(response);
if (response != null)
{
try
{
// convert the String response to a JSON object,
// because JSON is the response format Rotten Tomatoes uses
JSONObject jsonResponse = new JSONObject(response);
// fetch the array of movies in the response
JSONArray genres = jsonResponse.getJSONArray("genres");
Genres = new String[genres.length()];
for (int i = 0; i < genres.length(); i++)
{
JSONObject movie = genres.getJSONObject(i);
Genres[i] = movie.getString("genres");
}
// add each movie's title to an array
for(int i = 0; i < genres.length(); i++)
{
Toast.makeText(getBaseContext(), ""+Genres[i], Toast.LENGTH_SHORT).show();
}
}
catch (JSONException e)
{
Log.d("Test", "Failed to parse the JSON response!");
}
}
}
}
}
LogCat Output:
04-12 20:57:46.088: E/AndroidRuntime(593): FATAL EXCEPTION: main
04-12 20:57:46.088: E/AndroidRuntime(593): java.lang.RuntimeException: org.json.JSONException: Value Drama at 0 of type java.lang.String cannot be converted to JSONObject
04-12 20:57:46.088: E/AndroidRuntime(593): at akshat.jaiswal.rottenreviews.MovieInfo$RequestTask.onPostExecute(MovieInfo.java:106)
04-12 20:57:46.088: E/AndroidRuntime(593): at akshat.jaiswal.rottenreviews.MovieInfo$RequestTask.onPostExecute(MovieInfo.java:1)
04-12 20:57:46.088: E/AndroidRuntime(593): at android.os.AsyncTask.finish(AsyncTask.java:602)
04-12 20:57:46.088: E/AndroidRuntime(593): at android.os.AsyncTask.access$600(AsyncTask.java:156)
04-12 20:57:46.088: E/AndroidRuntime(593): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
04-12 20:57:46.088: E/AndroidRuntime(593): at android.os.Handler.dispatchMessage(Handler.java:99)
04-12 20:57:46.088: E/AndroidRuntime(593): at android.os.Looper.loop(Looper.java:154)
04-12 20:57:46.088: E/AndroidRuntime(593): at android.app.ActivityThread.main(ActivityThread.java:4624)
04-12 20:57:46.088: E/AndroidRuntime(593): at java.lang.reflect.Method.invokeNative(Native Method)
04-12 20:57:46.088: E/AndroidRuntime(593): at java.lang.reflect.Method.invoke(Method.java:511)
04-12 20:57:46.088: E/AndroidRuntime(593): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:809)
04-12 20:57:46.088: E/AndroidRuntime(593): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
04-12 20:57:46.088: E/AndroidRuntime(593): at dalvik.system.NativeStart.main(Native Method)
04-12 20:57:46.088: E/AndroidRuntime(593): Caused by: org.json.JSONException: Value Drama at 0 of type java.lang.String cannot be converted to JSONObject
04-12 20:57:46.088: E/AndroidRuntime(593): at org.json.JSON.typeMismatch(JSON.java:100)
04-12 20:57:46.088: E/AndroidRuntime(593): at org.json.JSONArray.getJSONObject(JSONArray.java:484)
04-12 20:57:46.088: E/AndroidRuntime(593): at akshat.jaiswal.rottenreviews.MovieInfo$RequestTask.onPostExecute(MovieInfo.java:91)
04-12 20:57:46.088: E/AndroidRuntime(593): ... 12 more
I am not able to parse objects like Title or release, is there something I am missing here?
Try something like:
// convert the String response to a JSON object,
// because JSON is the response format Rotten Tomatoes uses
JSONObject jsonResponse = new JSONObject(response);
//Array
JSONArray genres = jsonResponse.getJSONArray("genres");
// which gives you this:
// "genres": [
// "Animation",
// "Kids & Family",
// "Science Fiction & Fantasy",
// "Comedy"
// ]
//Now you can ask length
int howManyGenres = genres.length();
String[] genresStr = new String[howManyGenres];
//You can iterate here
for(int i=0; i<howManyGenres; i++) {
genresStr[i] = genres.get(i);
}
Related
My code is successfully retrieving the json data but not displaying in the app due to the error org.json.jsonarray cannot be converted to jsonobject.
I have tried to use JSONarray but that is triggering chain of other errors.
Please help:
here is my code:
public class Main7Activity extends AppCompatActivity {
public String username;
public String result;
EditText contents;
//public String result;
public EditText serial1;
public String serial;
StringBuilder content = new StringBuilder();
TextView myResultTxt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main7);
Intent intentExtras = getIntent();
Bundle extraBundle = intentExtras.getExtras();
username = extraBundle.getString("username");
serial1 = (EditText) findViewById(R.id.serial);
serial = serial1.getText().toString();
contents = (EditText) findViewById(R.id.contents);
Button ret = (Button) findViewById(R.id.ret);
myResultTxt = (TextView) findViewById(R.id.my_result);
}
public void ret(View v) {
serial = serial1.getText().toString();
if (TextUtils.isEmpty(serial)) {
serial1.setError("Please Enter the Serial Number");
} else {
try {
Log.w("var23", "api hit in start");
GetClass apiObj = new GetClass(this);
apiObj.url = "http://10.43.106.94:8080/SRNSmartLab/rest/service/getNEdata" + serial;
// apiObj.displayParm = "origin";
apiObj.execute();
Log.w("var23", "api hit in executed");
} catch (Exception e) {
result = e.getMessage();
Toast.makeText(Main7Activity.this, "" + result, Toast.LENGTH_LONG).show();
}
}
}
/* APi caller */
private class GetClass extends AsyncTask<String, Void, Void> {
private final Context context;
public String url;
public String displayParm;
public GetClass(Context c) {
this.context = c;
}
protected void onPreExecute() {
// progress= new ProgressDialog(this.context);
// progress.setMessage("Loading");
// progress.show();
Log.w("var23", "loading");
}
#Override
protected Void doInBackground(String... params) {
try {
Log.w("var23", "doInBackground url : " + this.url);
// final TextView outputView = (TextView) findViewById(R.id.showOutput);
URL url = new URL( this.url );
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// String urlParameters = "fizz=buzz";
connection.setRequestMethod("GET");
connection.setRequestProperty("USER-AGENT", "Mozilla/5.0");
connection.setRequestProperty("ACCEPT-LANGUAGE", "en-US,en;0.5");
int responseCode = connection.getResponseCode();
Log.w("var23", "api hit in respomse"+String.valueOf(responseCode));
final StringBuilder output = new StringBuilder("Request URL " + url);
output.append(System.getProperty("line.separator") + "Response Code " + responseCode);
output.append(System.getProperty("line.separator") + "Type " + "GET");
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = "";
StringBuilder responseOutput = new StringBuilder();
System.out.println("output===============" + br);
while ((line = br.readLine()) != null) {
responseOutput.append(line);
}
Log.w("var23", "Result from API: " + responseOutput.toString());
br.close();
final JSONObject jObject = new JSONObject(responseOutput.toString());
// final String myUrl = jObject.getString( this.displayParm );
String theData = System.getProperty("line.separator") + "Response " + System.getProperty("line.separator") + System.getProperty("line.separator") + responseOutput.toString();
Log.w("var24", "data: " + theData);
output.append(theData);
Main7Activity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// To display any content to ui
try {
myResultTxt.setText(jObject.getString("url"));
contents.setText(jObject.toString());
Log.w("var25", jObject.toString());
} catch (JSONException e) {
e.printStackTrace();
}
// outputView.setText(output);
// progress.dismiss();
}
});
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
Log.w("var26", "error MalformedURLException");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.w("var27", "error IOException");
e.printStackTrace();
} catch (JSONException e) {
Log.w("var28", "error JSON exception");
e.printStackTrace();
}
Log.w("var23", "end of the line");
return null;
}
}
JSON Output :
Output from AndroidStudio: Result from API: [{ "_id" : { "$oid" : "5784818bcb30b4918964b50f"} , "LabLocation" : "U02" , "RackLocation" : "EOI-Radio-B01" , "ShelfLocation" : "SH-01" , "VER" : "908762" , "Cluster" : "Radio" , "Name" : "BTS01-Coral-yun-SEW" , "SoftwareVersion" : "LN6.0" , "HardwareType" : "FRGP" , "AssetNo" : "108243" , "SerialNO" : "RY114208612" , "Location" : "zzccg" , "Uname" : "addtvI"}]
Stack Trace :
07-15 10:07:28.750 6240-6240/com.example.manv.nokialabs W/var23: api hit in start
07-15 10:07:28.755 6240-6240/com.example.manv.nokialabs W/var23: loading
07-15 10:07:28.756 6240-6240/com.example.manv.nokialabs W/var23: api hit in executed
07-15 10:07:28.756 6240-6290/com.example.manv.nokialabs W/var23: doInBackground url : http://10.43.106.94:8080/SRNSmartLab/rest/service/getNEdataRY114208612
07-15 10:07:28.758 6240-6290/com.example.manv.nokialabs W/System: ClassLoader referenced unknown path: /system/framework/tcmclient.jar
07-15 10:07:28.802 6240-6290/com.example.manv.nokialabs W/var23: api hit in respomse200
07-15 10:07:28.804 6240-6290/com.example.manv.nokialabs I/System.out: output===============java.io.BufferedReader#506b410
07-15 10:07:28.805 6240-6290/com.example.manv.nokialabs W/var23: Result from API: [{ "_id" : { "$oid" : "5784818bcb30b4918964b50f"} , "LabLocation" : "U02" , "RackLocation" : "EOI-Radio-B01" , "ShelfLocation" : "SH-01" , "VER" : "908762" , "Cluster" : "Radio" , "Name" : "BTS01-Coral-yun-SEW" , "SoftwareVersion" : "LN6.0" , "HardwareType" : "FRGP" , "AssetNo" : "108243" , "SerialNO" : "RY114208612" , "Location" : "zzccg" , "Uname" : "addtvI"}]
07-15 10:07:28.807 6240-6290/com.example.manv.nokialabs W/var28: error JSON exception
07-15 10:07:28.808 6240-6290/com.example.manv.nokialabs W/System.err: org.json.JSONException: Value [{"_id":{"$oid":"5784818bcb30b4918964b50f"},"LabLocation":"U02","RackLocation":"EOI-Radio-B01","ShelfLocation":"SH-01","VER":"908762","Cluster":"Radio","Name":"BTS01-Coral-yun-SEW","SoftwareVersion":"LN6.0","HardwareType":"FRGP","AssetNo":"108243","SerialNO":"RY114208612","Location":"zzccg","Uname":"addtvI"}] of type org.json.JSONArray cannot be converted to JSONObject
07-15 10:07:28.808 6240-6290/com.example.manv.nokialabs W/System.err: at org.json.JSON.typeMismatch(JSON.java:111)
07-15 10:07:28.808 6240-6290/com.example.manv.nokialabs W/System.err: at org.json.JSONObject.<init>(JSONObject.java:160)
07-15 10:07:28.808 6240-6290/com.example.manv.nokialabs W/System.err: at org.json.JSONObject.<init>(JSONObject.java:173)
07-15 10:07:28.808 6240-6290/com.example.manv.nokialabs W/System.err: at com.example.albbaby.nokialabs.Main7Activity$GetClass.doInBackground(Main7Activity.java:172)
07-15 10:07:28.808 6240-6290/com.example.manv.nokialabs W/System.err: at com.example.albbaby.nokialabs.Main7Activity$GetClass.doInBackground(Main7Activity.java:127)
07-15 10:07:28.808 6240-6290/com.example.manv.nokialabs W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:295)
07-15 10:07:28.809 6240-6290/com.example.manv.nokialabs W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
07-15 10:07:28.809 6240-6290/com.example.manv.nokialabs W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
07-15 10:07:28.809 6240-6290/com.example.manv.nokialabs W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
07-15 10:07:28.809 6240-6290/com.example.manv.nokialabs W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
07-15 10:07:28.809 6240-6290/com.example.manv.nokialabs W/System.err: at java.lang.Thread.run(Thread.java:818)
07-15 10:07:28.809 6240-6290/com.example.manv.nokialabs W/var23: end of the line
Reponse contains JsonArray but your trying to convert into JsonObject Thats way it showing error.(org.json.jsonarray cannot be converted to jsonobject.)
Previous code:
final JSONObject jObject = new JSONObject(responseOutput.toString());
Change it as below line:
final JSONArray jArrayObj= new JSONArray (responseOutput.toString());
You are trying to convert JSONArray into JSONObject.
Use this
final JSONArray jArray = new JSONArray(responseOutput.toString());
I got error when I tried to upload all of the images. I use for to loop the process, but still got error in looping. if i don't use for, it still can upload the image but only 1 image that will be uploaded. how can I solve this?
UploadActivity.java
Intent intent = getIntent();
filePath = intent.getStringExtra("filePath");
ArrayList<String> flpath = new ArrayList<String>();
SharedPreferences prefs = getSharedPreferences("SavedFilePathsJSONArray",
Context.MODE_PRIVATE);
String myJSONArrayString = prefs.getString("SavedFilePathsJSONArray",
"");
if (!myJSONArrayString.isEmpty()) {
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(myJSONArrayString);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < jsonArray.length(); i++) {
try {
flpath.add(jsonArray.get(i).toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
flpath.add(filePath);
JSONArray mJSONArray = new JSONArray(flpath);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("SavedFilePathsJSONArray", mJSONArray.toString()).commit();
for (int i = 0; i < flpath.size(); i++) {
imgFile = new File(flpath.get(i));
if (imgFile.exists()) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath(),options);
ImageView myImage = new ImageView(this);
myImage.setMaxHeight(100);
myImage.setMaxWidth(100);
myImage.setImageBitmap(myBitmap);
layout2.addView(myImage);
}
}
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
// setting progress bar to zero
progressBar.setProgress(0);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
// Making progress bar visible
progressBar.setVisibility(View.VISIBLE);
// updating progress bar value
progressBar.setProgress(progress[0]);
// updating percentage value
txtPercentage.setText(String.valueOf(progress[0]) + "%");
}
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
for (int i = 0; i < flPath.size(); i++) {
File file = new File( flPath.get(i));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
// Adding file data to http body
entity.addPart("image", new FileBody(file));
// Extra parameters if you want to pass to server
entity.addPart("website",
new StringBody("www.androidhive.info"));
entity.addPart("email", new StringBody("abc#gmail.com"));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
}
return responseString;
}
Config.Java
public class Config {
public static final String FILE_UPLOAD_URL = "http://....";
// Directory name to store captured images and videos
public static final String IMAGE_DIRECTORY_NAME = "andrd_upload";
}
error logcat
01-27 16:23:45.940: W/dalvikvm(15986): threadid=12: thread exiting with uncaught exception (group=0x40fe7438)
01-27 16:23:45.950: E/AndroidRuntime(15986): FATAL EXCEPTION: AsyncTask #1
01-27 16:23:45.950: E/AndroidRuntime(15986): java.lang.RuntimeException: An error occured while executing doInBackground()
01-27 16:23:45.950: E/AndroidRuntime(15986): at android.os.AsyncTask$3.done(AsyncTask.java:299)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-27 16:23:45.950: E/AndroidRuntime(15986): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.lang.Thread.run(Thread.java:856)
01-27 16:23:45.950: E/AndroidRuntime(15986): Caused by: java.lang.NullPointerException
01-27 16:23:45.950: E/AndroidRuntime(15986): at com.camerafileupload.UploadActivity$UploadFileToServer.uploadFile(UploadActivity.java:228)
01-27 16:23:45.950: E/AndroidRuntime(15986): at com.camerafileupload.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:221)
01-27 16:23:45.950: E/AndroidRuntime(15986): at com.camerafileupload.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:1)
01-27 16:23:45.950: E/AndroidRuntime(15986): at android.os.AsyncTask$2.call(AsyncTask.java:287)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
01-27 16:23:45.950: E/AndroidRuntime(15986): ... 5 more
01-27 16:23:46.130: D/HardwareRenderer(15986): draw surface is valid dirty= null
01-27 16:23:46.180: D/HardwareRenderer(15986): draw surface is valid dirty= null
01-27 16:23:46.220: D/HardwareRenderer(15986): draw surface is valid dirty= null
01-27 16:25:29.910: D/dalvikvm(15986): WAIT_FOR_CONCURRENT_GC blocked 0ms
01-27 16:25:29.950: D/dalvikvm(15986): GC_EXPLICIT freed 223K, 8% free 15337K/16583K, paused 2ms+4ms, total 38ms
ScreenShoot
Edit: i put the error logcat and the screenshoot of the error page (UploadActivity.java).
I am trying to store the data entered by user to MySQL database using PHP in my android app. But whenever the button is clicked, i receive this message "Unfortunately, [app] has stopped working."
public class Register extends Activity implements View.OnClickListener {
private EditText userName, userContact, userAddress, userRequest;
private Spinner userStore;
private Button mRegister;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
//php login script
//localhost :
//testing on your device
//put your local ip instead, on windows, run CMD > ipconfig
//or in mac's terminal type ifconfig and look for the ip under en0 or en1
// private static final String LOGIN_URL = "http://xxx.xxx.x.x:1234/webservice/register.php";
//testing on Emulator:
private static final String LOGIN_URL = "http://10.0.2.2/callarocket/register.php";
//testing from a real server:
//private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/register.php";
//ids
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.first_screen);
Spinner dropdown = (Spinner)findViewById(R.id.StoreSpinner);
String[] items = new String[]{"NZ Mamak", "Indo Shop", "NZ Supermarket"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items);
dropdown.setAdapter(adapter);
userName = (EditText)findViewById(R.id.EditName);
userContact = (EditText)findViewById(R.id.EditContact);
userAddress = (EditText)findViewById(R.id.EditAddress);
userStore = (Spinner)findViewById(R.id.StoreSpinner);
userRequest = (EditText)findViewById(R.id.EditRequest);
mRegister = (Button)findViewById(R.id.SubmitButton);
mRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new CreateUser().execute();
}
class CreateUser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Register.this);
pDialog.setMessage("Creating Request...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = userName.getText().toString();
String usercontact = userContact.getText().toString();
String useraddress = userAddress.getText().toString();
String userstore = userStore.getSelectedItem().toString();
String userrequest = userRequest.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("userName", username));
params.add(new BasicNameValuePair("userContact", usercontact));
params.add(new BasicNameValuePair("userAddress", useraddress));
params.add(new BasicNameValuePair("userStore", userstore));
params.add(new BasicNameValuePair("userRequest", userrequest));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// full json response
Log.d("Login attempt", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("User Created!", json.toString());
finish();
return json.getString(TAG_MESSAGE);
}else{
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} 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();
if (file_url != null){
Toast.makeText(Register.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
And here is my JSONParser code.
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(final String url) {
// Making HTTP request
try {
// Construct the client and the HTTP request.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
// Execute the POST request and store the response locally.
HttpResponse httpResponse = httpClient.execute(httpPost);
// Extract data from the response.
HttpEntity httpEntity = httpResponse.getEntity();
// Open an inputStream with the data content.
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
// Create a BufferedReader to parse through the inputStream.
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
// Declare a string builder to help with the parsing.
StringBuilder sb = new StringBuilder();
// Declare a string to store the JSON object data in string form.
String line = null;
// Build the string until null.
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
// Close the input stream.
is.close();
// Convert the string builder data to an actual string.
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// Try to 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 the JSON Object.
return jObj;
}
// 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 {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
And here is the logcat
02-25 11:25:36.224 2445-2460/com.example.user.callarocket D/OpenGLRenderer﹕ Render dirty regions requested: true
02-25 11:25:36.228 2445-2445/com.example.user.callarocket D/﹕ HostConnection::get() New Host Connection established 0xa6c43550, tid 2445
02-25 11:25:36.271 2445-2445/com.example.user.callarocket D/Atlas﹕ Validating map...
02-25 11:25:36.373 2445-2460/com.example.user.callarocket D/﹕ HostConnection::get() New Host Connection established 0xa6c438d0, tid 2460
02-25 11:25:36.423 2445-2460/com.example.user.callarocket I/OpenGLRenderer﹕ Initialized EGL, version 1.4
02-25 11:25:36.457 2445-2460/com.example.user.callarocket D/OpenGLRenderer﹕ Enabling debug mode 0
02-25 11:25:36.500 2445-2460/com.example.user.callarocket W/EGL_emulation﹕ eglSurfaceAttrib not implemented
02-25 11:25:36.500 2445-2460/com.example.user.callarocket W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xae1eb880, error=EGL_SUCCESS
02-25 11:25:48.014 2445-2460/com.example.user.callarocket W/EGL_emulation﹕ eglSurfaceAttrib not implemented
02-25 11:25:48.014 2445-2460/com.example.user.callarocket W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa5b6d2a0, error=EGL_SUCCESS
02-25 11:25:48.303 2445-2460/com.example.user.callarocket D/OpenGLRenderer﹕ endAllStagingAnimators on 0xa6cb7580 (RippleDrawable) with handle 0xa6c43c60
02-25 11:25:59.147 2445-2465/com.example.user.callarocket D/request!﹕ starting
02-25 11:25:59.207 2445-2460/com.example.user.callarocket W/EGL_emulation﹕ eglSurfaceAttrib not implemented
02-25 11:25:59.207 2445-2460/com.example.user.callarocket W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xae1f3be0, error=EGL_SUCCESS
02-25 11:25:59.281 2445-2465/com.example.user.callarocket E/JSON Parser﹕ Error parsing data org.json.JSONException: Value Posted of type java.lang.String cannot be converted to JSONObject
02-25 11:25:59.299 2445-2465/com.example.user.callarocket E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.example.user.callarocket, PID: 2445
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
at com.example.user.callarocket.Register$CreateUser.doInBackground(Register.java:128)
at com.example.user.callarocket.Register$CreateUser.doInBackground(Register.java:85)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
02-25 11:25:59.599 2445-2460/com.example.user.callarocket W/EGL_emulation﹕ eglSurfaceAttrib not implemented
02-25 11:25:59.599 2445-2460/com.example.user.callarocket W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xae1f3e60, error=EGL_SUCCESS
02-25 11:26:00.172 2445-2445/com.example.user.callarocket E/WindowManager﹕ android.view.WindowLeaked: Activity com.example.user.callarocket.Register has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{2dbde5f6 V.E..... R......D 0,0-1026,348} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:363)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:261)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:298)
at com.example.user.callarocket.Register$CreateUser.onPreExecute(Register.java:99)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.example.user.callarocket.Register.onClick(Register.java:81)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
After Log.i("DATA",json) is added
02-25 12:24:16.222 2750-2765/com.example.user.callarocket D/OpenGLRenderer﹕ Render dirty regions requested: true
02-25 12:24:16.225 2750-2750/com.example.user.callarocket D/﹕ HostConnection::get() New Host Connection established 0xa6c3e550, tid 2750
02-25 12:24:16.259 2750-2750/com.example.user.callarocket D/Atlas﹕ Validating map...
02-25 12:24:16.366 2750-2765/com.example.user.callarocket D/﹕ HostConnection::get() New Host Connection established 0xa6c3e6f0, tid 2765
02-25 12:24:16.405 2750-2765/com.example.user.callarocket I/OpenGLRenderer﹕ Initialized EGL, version 1.4
02-25 12:24:16.433 2750-2765/com.example.user.callarocket D/OpenGLRenderer﹕ Enabling debug mode 0
02-25 12:24:16.462 2750-2765/com.example.user.callarocket W/EGL_emulation﹕ eglSurfaceAttrib not implemented
02-25 12:24:16.462 2750-2765/com.example.user.callarocket W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa6c118a0, error=EGL_SUCCESS
02-25 12:24:24.841 2750-2765/com.example.user.callarocket W/EGL_emulation﹕ eglSurfaceAttrib not implemented
02-25 12:24:24.842 2750-2765/com.example.user.callarocket W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa5e39720, error=EGL_SUCCESS
02-25 12:24:25.095 2750-2765/com.example.user.callarocket D/OpenGLRenderer﹕ endAllStagingAnimators on 0xa6cb2580 (RippleDrawable) with handle 0xa6c3eab0
02-25 12:24:33.820 2750-2768/com.example.user.callarocket D/request!﹕ starting
02-25 12:24:33.862 2750-2765/com.example.user.callarocket W/EGL_emulation﹕ eglSurfaceAttrib not implemented
02-25 12:24:33.863 2750-2765/com.example.user.callarocket W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa5605140, error=EGL_SUCCESS
02-25 12:24:34.027 2750-2768/com.example.user.callarocket E/JSON Parser﹕ Error parsing data org.json.JSONException: Value Posted of type java.lang.String cannot be converted to JSONObject
02-25 12:24:34.028 2750-2768/com.example.user.callarocket E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.example.user.callarocket, PID: 2750
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
at com.example.user.callarocket.Register$CreateUser.doInBackground(Register.java:128)
at com.example.user.callarocket.Register$CreateUser.doInBackground(Register.java:85)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
02-25 12:24:34.335 2750-2765/com.example.user.callarocket W/EGL_emulation﹕ eglSurfaceAttrib not implemented
02-25 12:24:34.335 2750-2765/com.example.user.callarocket W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa5af7e00, error=EGL_SUCCESS
02-25 12:24:36.361 2750-2750/com.example.user.callarocket I/Choreographer﹕ Skipped 106 frames! The application may be doing too much work on its main thread.
02-25 12:24:36.754 2750-2750/com.example.user.callarocket E/WindowManager﹕ android.view.WindowLeaked: Activity com.example.user.callarocket.Register has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{2dbde5f6 V.E..... R......D 0,0-1026,348} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:363)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:261)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:298)
at com.example.user.callarocket.Register$CreateUser.onPreExecute(Register.java:99)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.example.user.callarocket.Register.onClick(Register.java:81)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
You have problem in.
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new CreateUser().execute();
}
here you have to use which button is clicked. normally we use
switch(v.getId())
{
case your button id :
//Button function
}
You need to be using a parser to parse the string and then cast it to a JSONObject like so -
JSONParser parser = new JSONParser();
Object obj = parser.parse(json);
JSONObject jsonObj = (JSONObject) obj;
return jsonObj;
I am very new in using JSON in Android. I have got the webAPI that the base URL is
Test server. While developing, I am trying to login using email and password from web server database.
A user token is calculated by following formula:
Token = MD5(email + userId); I do not know what is this. What I tried to do is ;
JSONParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
System.out.println("url:: "+url );
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
// Create a BufferedReader to parse through the inputStream.
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
// Declare a string builder to help with the parsing.
StringBuilder sb = new StringBuilder();
// Declare a string to store the JSON object data in string form.
String line = null;
// Build the string until null.
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
// Close the input stream.
is.close();
// Convert the string builder data to an actual string.
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;
}
// 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 the request method
if(method == "POST"){
//request method to post
//default HTTPClient
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 to 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;
}
}
Login.java
public class Login extends Activity {
EditText inputEmail;
EditText inputPassword;
Button loginBtn;
// Progress Dialog
ProgressDialog pDialog;
// JSONParser class
JSONParser jsonParser = new JSONParser();
// PHP Login Script location
private static final String LOGIN_URL = "http://www.sthng.com/ws/?c=profile&func=login";
// JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "Success";
private static final String TAG_MESSAGE = "Message";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
loginBtn = (Button) findViewById(R.id.btnLogin);
loginBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new AttemptLogin().execute();
}
});
}
// AsyncTask is a seperate thread than the thread that runs the GUI
// Any type of networking should be done with asynctask.
class AttemptLogin extends AsyncTask<String, Void, String> {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Attempting login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
//params.add(new BasicNameValuePair("RegistrationID", ));
// Log.d("HERE", email);
// Log.d("HERE2", password);
Log.d("request!", "starting");
// getting users details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "GET", params);
Log.d("DEBUG!", "CHECKPOINT");
// json = json.toString();
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
/* Intent i = new Intent(Login.this, Home.class);
finish();
startActivity(i);*/
return json.getString(TAG_MESSAGE);
} else {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
pDialog.dismiss();
if (file_url != null) {
Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
But I am getting error like;
04-29 19:03:22.691: D/request!(15060): starting
04-29 19:03:22.736: D/dalvikvm(15060): GC_CONCURRENT freed 222K, 14% free 9575K/11015K, paused 13ms+22ms, total 82ms
04-29 19:03:22.781: W/dalvikvm(15060): threadid=11: thread exiting with uncaught exception (group=0x41d082a0)
04-29 19:03:22.791: E/AndroidRuntime(15060): FATAL EXCEPTION: AsyncTask #1
04-29 19:03:22.791: E/AndroidRuntime(15060): java.lang.RuntimeException: An error occured while executing doInBackground()
04-29 19:03:22.791: E/AndroidRuntime(15060): at android.os.AsyncTask$3.done(AsyncTask.java:299)
04-29 19:03:22.791: E/AndroidRuntime(15060): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
04-29 19:03:22.791: E/AndroidRuntime(15060): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
04-29 19:03:22.791: E/AndroidRuntime(15060): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
04-29 19:03:22.791: E/AndroidRuntime(15060): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
04-29 19:03:22.791: E/AndroidRuntime(15060): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
04-29 19:03:22.791: E/AndroidRuntime(15060): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
04-29 19:03:22.791: E/AndroidRuntime(15060): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
04-29 19:03:22.791: E/AndroidRuntime(15060): at java.lang.Thread.run(Thread.java:856)
04-29 19:03:22.791: E/AndroidRuntime(15060): Caused by: java.lang.IllegalArgumentException: Host name may not be null
04-29 19:03:22.791: E/AndroidRuntime(15060): at org.apache.http.HttpHost.<init>(HttpHost.java:83)
04-29 19:03:22.791: E/AndroidRuntime(15060): at org.apache.http.impl.client.AbstractHttpClient.determineTarget(AbstractHttpClient.java:519)
04-29 19:03:22.791: E/AndroidRuntime(15060): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:509)
04-29 19:03:22.791: E/AndroidRuntime(15060): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
04-29 19:03:22.791: E/AndroidRuntime(15060): at com.example.sthng.JSONParser.makeHttpRequest(JSONParser.java:125)
04-29 19:03:22.791: E/AndroidRuntime(15060): at com.example.sthng.Login$AttemptLogin.doInBackground(Login.java:106)
04-29 19:03:22.791: E/AndroidRuntime(15060): at com.example.sthng.Login$AttemptLogin.doInBackground(Login.java:1)
04-29 19:03:22.791: E/AndroidRuntime(15060): at android.os.AsyncTask$2.call(AsyncTask.java:287)
04-29 19:03:22.791: E/AndroidRuntime(15060): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
04-29 19:03:22.791: E/AndroidRuntime(15060): ... 5 more
04-29 19:03:32.686: I/Choreographer(15060): Skipped 589 frames! The application may be doing too much work on its main thread.
04-29 19:03:33.256: E/WindowManager(15060): Activity com.example.sthng.Login has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#427a0298 that was originally added here
04-29 19:03:33.256: E/WindowManager(15060): android.view.WindowLeaked: Activity com.example.clipme.Login has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#427a0298 that was originally added here
04-29 19:03:33.256: E/WindowManager(15060): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:403)
04-29 19:03:33.256: E/WindowManager(15060): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:311)
04-29 19:03:33.256: E/WindowManager(15060): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224)
04-29 19:03:33.256: E/WindowManager(15060): at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149)
04-29 19:03:33.256: E/WindowManager(15060): at android.view.Window$LocalWindowManager.addView(Window.java:554)
04-29 19:03:33.256: E/WindowManager(15060): at android.app.Dialog.show(Dialog.java:277)
04-29 19:03:33.256: E/WindowManager(15060): at com.example.sthng.Login$AttemptLogin.onPreExecute(Login.java:87)
04-29 19:03:33.256: E/WindowManager(15060): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
04-29 19:03:33.256: E/WindowManager(15060): at android.os.AsyncTask.execute(AsyncTask.java:534)
04-29 19:03:33.256: E/WindowManager(15060): at com.example.sthng.Login$1.onClick(Login.java:61)
04-29 19:03:33.256: E/WindowManager(15060): at android.view.View.performClick(View.java:4232)
04-29 19:03:33.256: E/WindowManager(15060): at android.view.View$PerformClick.run(View.java:17298)
04-29 19:03:33.256: E/WindowManager(15060): at android.os.Handler.handleCallback(Handler.java:615)
04-29 19:03:33.256: E/WindowManager(15060): at android.os.Handler.dispatchMessage(Handler.java:92)
04-29 19:03:33.256: E/WindowManager(15060): at android.os.Looper.loop(Looper.java:137)
04-29 19:03:33.256: E/WindowManager(15060): at android.app.ActivityThread.main(ActivityThread.java:4921)
04-29 19:03:33.256: E/WindowManager(15060): at java.lang.reflect.Method.invokeNative(Native Method)
04-29 19:03:33.256: E/WindowManager(15060): at java.lang.reflect.Method.invoke(Method.java:511)
04-29 19:03:33.256: E/WindowManager(15060): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
04-29 19:03:33.256: E/WindowManager(15060): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
04-29 19:03:33.256: E/WindowManager(15060): at dalvik.system.NativeStart.main(Native Method)
I am sure I have done some stupid mistake but please do not take it bad way. I hope I get some hints and solutions for this.
You are accessing UI element doInBackground()
Intent i = new Intent(Login.this, Home.class);
finish();
startActivity(i);
above method on doInBackground(). You have to call this method onPostExecute.
you are sending email and password two time.
You make url with https:sthng.com/ws?function=login&email=" + email+ "&password=" + password
JSONObject json = jsonParser.makeHttpRequest(
"https:sthng.com/ws?function=login&email=" + email
+ "&password=" + password, "POST", params);
or
Now you make below param.
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("androidToken", androidToken));// your token
and passing again
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));// passing again
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Here is my structure of JSON
URL::
http://54.218.73.244:7004/DescriptionSortedPrice/
JSON ::
{
"restaurants": [
{
"Sl_no": 1,
"Person_Name": "salmanKhan",
"Image_Name": "image.jpg"
},
Adapter.java
public class Adapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
HashMap<String, String> resultp = new HashMap<String, String>();
public Adapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView name;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.single_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
name = (TextView) itemView.findViewById(R.id.title_textView_id);
// Capture position and set results to the TextViews
name.setText(resultp.get(MainActivity.NAME));
return itemView;
}
}
MainActivity.java
public class MainActivity extends Activity{
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
Adapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String NAME = "rank";
String TYPE_FILTER;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.activity_main);
listview = (ListView) findViewById(R.id.listView_id);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
//mProgressDialog.setTitle("Fetching the information");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = Parser.getJSONfromURL("http://54.218.73.244:7004/DescriptionSortedPrice/");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("restaurants");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put(MainActivity.NAME, jsonobject.getString("Person_Name"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Pass the results into ListViewAdapter.java
adapter = new Adapter(MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
Parser.java
public class Parser {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
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;
}
}
Log::
01-01 12:13:14.600: E/log_tag(715): Error in http connection java.net.SocketException: Permission denied
01-01 12:13:14.610: E/log_tag(715): Error converting result java.lang.NullPointerException
01-01 12:13:14.620: E/log_tag(715): Error parsing data org.json.JSONException: End of input at character 0 of
01-01 12:13:14.660: W/dalvikvm(715): threadid=7: thread exiting with uncaught exception (group=0x4001d800)
01-01 12:13:14.690: E/AndroidRuntime(715): FATAL EXCEPTION: AsyncTask #1
01-01 12:13:14.690: E/AndroidRuntime(715): java.lang.RuntimeException: An error occured while executing doInBackground()
01-01 12:13:14.690: E/AndroidRuntime(715): at android.os.AsyncTask$3.done(AsyncTask.java:200)
01-01 12:13:14.690: E/AndroidRuntime(715): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
01-01 12:13:14.690: E/AndroidRuntime(715): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
01-01 12:13:14.690: E/AndroidRuntime(715): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
01-01 12:13:14.690: E/AndroidRuntime(715): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-01 12:13:14.690: E/AndroidRuntime(715): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
01-01 12:13:14.690: E/AndroidRuntime(715): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
01-01 12:13:14.690: E/AndroidRuntime(715): at java.lang.Thread.run(Thread.java:1096)
01-01 12:13:14.690: E/AndroidRuntime(715): Caused by: java.lang.NullPointerException
01-01 12:13:14.690: E/AndroidRuntime(715): at com.example.singleitemlistview.MainActivity$DownloadJSON.doInBackground(MainActivity.java:71)
01-01 12:13:14.690: E/AndroidRuntime(715): at com.example.singleitemlistview.MainActivity$DownloadJSON.doInBackground(MainActivity.java:1)
01-01 12:13:14.690: E/AndroidRuntime(715): at android.os.AsyncTask$2.call(AsyncTask.java:185)
01-01 12:13:14.690: E/AndroidRuntime(715): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
01-01 12:13:14.690: E/AndroidRuntime(715): ... 4 more
01-01 12:13:17.215: E/WindowManager(715): Activity com.example.singleitemlistview.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#45fbe1e8 that was originally added here
01-01 12:13:17.215: E/WindowManager(715): android.view.WindowLeaked: Activity com.example.singleitemlistview.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#45fbe1e8 that was originally added here
01-01 12:13:17.215: E/WindowManager(715): at android.view.ViewRoot.<init>(ViewRoot.java:247)
01-01 12:13:17.215: E/WindowManager(715): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
01-01 12:13:17.215: E/WindowManager(715): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
01-01 12:13:17.215: E/WindowManager(715): at android.view.Window$LocalWindowManager.addView(Window.java:424)
01-01 12:13:17.215: E/WindowManager(715): at android.app.Dialog.show(Dialog.java:241)
01-01 12:13:17.215: E/WindowManager(715): at com.example.singleitemlistview.MainActivity$DownloadJSON.onPreExecute(MainActivity.java:58)
01-01 12:13:17.215: E/WindowManager(715): at android.os.AsyncTask.execute(AsyncTask.java:391)
01-01 12:13:17.215: E/WindowManager(715): at com.example.singleitemlistview.MainActivity.onCreate(MainActivity.java:41)
01-01 12:13:17.215: E/WindowManager(715): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-01 12:13:17.215: E/WindowManager(715): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
01-01 12:13:17.215: E/WindowManager(715): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
01-01 12:13:17.215: E/WindowManager(715): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
01-01 12:13:17.215: E/WindowManager(715): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
01-01 12:13:17.215: E/WindowManager(715): at android.os.Handler.dispatchMessage(Handler.java:99)
01-01 12:13:17.215: E/WindowManager(715): at android.os.Looper.loop(Looper.java:123)
01-01 12:13:17.215: E/WindowManager(715): at android.app.ActivityThread.main(ActivityThread.java:4627)
01-01 12:13:17.215: E/WindowManager(715): at java.lang.reflect.Method.invokeNative(Native Method)
01-01 12:13:17.215: E/WindowManager(715): at java.lang.reflect.Method.invoke(Method.java:521)
01-01 12:13:17.215: E/WindowManager(715): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-01 12:13:17.215: E/WindowManager(715): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-01 12:13:17.215: E/WindowManager(715): at dalvik.system.NativeStart.main(Native Method)
referencing from log::
line 58:: mProgressDialog.show();
line41:: new DownloadJSON().execute();
line71:: map.put(MainActivity.NAME, jsonobject.getString("Person_Name"));
Problem:: I am not able to display the parsed items on my listview
Have you given the permission in your manifest
<uses-permission android:name="android.permission.INTERNET" />
because from your log you are getting
http connection java.net.SocketException: Permission denied
Which occurs when you don't give the internet permission and try to access internet.
From your log shows:
Error in http connection java.net.SocketException: Permission denied
Error converting result java.lang.NullPointerException
Error parsing data org.json.JSONException: End of input at character 0 of
Make sure you have given the INTERNET permission in your manifest.
<uses-permission android:name="android.permission.INTERNET" />
Also change your adapter method as below:
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
Update your parser with this code block
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, HTTP.UTF_8));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}