1

I'm developing an android application based on remote database , I found solutions on how to put data in the database but I'm having much problems on getting it back. When I open the activity that gets the data the app crash. I couldn't localise where the error is in my code!! so here is my code and I hope you can help me . Thank you.

This is "Acceuil" class that has 1 button to open "Professors" class.

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;


//in this class I'm just defining a button that will open another class to get data from the database.

public class Acceuil extends Activity  {
	
	
	Button b1;
	

	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.acceuil);
		
		b1 = (Button) findViewById(R.id.button3);
		
		b1.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
			
				Intent i = new Intent(getApplicationContext(), Professors.class);
				startActivity(i);
				
			}
		});
		
		
		
		
		

	}
}

This is the "Professors" class that crashes my app.

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class Professors extends Activity {
	
	
	
	//URL to get JSON Array
		private static  String url = "http://waelhamda.host22.com/comments.php";
		
		//JSON Node Names 
		private static final String TAG_USER = "posts";
		private static final String TAG_ID = "last";
		
		
		JSONArray user = null;



	    @Override
	    protected void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	      
	        setContentView(R.layout.professors);
	        
			// Creating new JSON Parser
			JSONParser jParser = new JSONParser();

			// Getting JSON from URL
			JSONObject json = jParser.getJSONFromUrl(url);
			
			try {
				// Getting JSON Array
				user = json.getJSONArray(TAG_USER);
				JSONObject c = user.getJSONObject(0);
				
				// Storing  JSON item in a Variable
				String id = c.getString(TAG_ID);
			
				
				//Importing TextView
				final TextView uid = (TextView)findViewById(R.id.pro1);
			
				
				//Set JSON Data in TextView
				uid.setText(id);
				

			
		} catch (JSONException e) {
			e.printStackTrace();
		}

				

	    }


	 
	    
	}

This is the "JSONParser" class.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;


 
import android.util.Log;
 
public class JSONParser {
 
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
 
    // constructor
    public JSONParser() {
 
    }
 
    
    
    
   

    	public JSONObject getJSONFromUrl(String 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 {
    			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;

    	}
    
    
    
    
    
    
    
    // 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 finally this is the manifest file of the app.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.wael.enimcommunity"
    android:versionCode="1"
    android:versionName="1.0" >
    
    
<meta-data android:name="com.google.android.backup.api_key" 
        android:value="AEdPqrEAAAAIdPJ8uLgoiErqlZNYU5_jN_d8O8VPPtfbbF5MRQ" />


    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />
    
     <uses-permission android:name="android.permission.INTERNET"/>

    <uses-permission 
        android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.wael.enimcommunity.Login"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.wael.enimcommunity.Register"
            android:label="@string/app_name"  >
        </activity>
        <activity
            android:name="com.wael.enimcommunity.Acceuil"
            android:label="@string/app_name"  >
        </activity>
        <activity
            android:name="com.wael.enimcommunity.JSONParser"
            android:label="@string/app_name"  >
        </activity>
        <activity
            android:name="com.wael.enimcommunity.GPSTracker"
            android:label="@string/app_name"  >
        </activity>
        <activity
            android:name="com.wael.enimcommunity.Events"
            android:label="@string/app_name"  >
        </activity>
        <activity
            android:name="com.wael.enimcommunity.Professors"
            android:label="@string/app_name"  >
        </activity>

        <activity
            android:name="com.wael.enimcommunity.Portail"
            android:label="@string/app_name"  >
        </activity>
        <activity
            android:name="com.wael.enimcommunity.Schedule"
            android:label="@string/app_name"  >
        </activity>
    </application>

</manifest>

I hope those informations are enough to solve my problem. Thanx again my friends.

8
  • 1
    Please post your logcat output with the errors you are receiving Commented Mar 3, 2015 at 21:58
  • Why don't you start by posting the allegedly faulty JSON message ? Commented Mar 3, 2015 at 22:00
  • Sorry my friend but i'm testing on my real device because the emulator didn't work on my laptop . Commented Mar 3, 2015 at 22:00
  • For one your web host is adding things to your "json" file, so it is not valid json. Also, your response headers from your server are "text/html; charset=utf-8" They should be json Commented Mar 3, 2015 at 22:01
  • @waelbenhamda You can still get logcat output from a real device. And without it, it is very difficult to troubleshoot your issue Commented Mar 3, 2015 at 22:02

2 Answers 2

1

You are networking in main thread. You need to fix this first.

Use AsyncTask

Example:

private TextView uid; // Define global

In onCreate

uid = (TextView)findViewById(R.id.pro1);

new MyAsyncTask().execute();

Inner class

public class MyAsyncTask extends AsyncTask<Void, Void, String> {

 @Override
 public String doInBackground(Void a) {
            JSONParser jParser = new JSONParser();

            // Getting JSON from URL
            JSONObject json = jParser.getJSONFromUrl(url);

        try {
                // Getting JSON Array
                user = json.getJSONArray(TAG_USER);
                JSONObject c = user.getJSONObject(0);

                // Storing  JSON item in a Variable
                String id = c.getString(TAG_ID);

                return id;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
 }

 public void onPostExecute(String result) {
    uid.setText(result);
 }

}
Sign up to request clarification or add additional context in comments.

Comments

0

Network operations can involve unpredictable delays. To prevent this from causing a poor user experience, always perform network operations on a separate thread from the UI. The AsyncTask class provides one of the simplest ways to fire off a new task from the UI thread.

Connecting to the Network

1 Comment

Invalid JSON remains invalid JSON, no matter the delay or the user experience.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.