0

MainActivity.java

package com.example.yashpachisia.fetchjson;

import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;


public class MainActivity extends ActionBarActivity {

    String myJSON;

    private static final String TAG_RESULTS="result";
    private static final String TAG_NAME = "name";
    private static final String TAG_AGE = "age";
    private static final String TAG_SEX ="sex";

    JSONArray peoples = null;

    ArrayList<HashMap<String, String>> personList;

    ListView list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        list = (ListView) findViewById(R.id.listView);
        personList = new ArrayList<HashMap<String,String>>();
        getData();
    }


    protected void showList(){
        try {
            JSONObject jsonObj = new JSONObject(myJSON);
            peoples = jsonObj.getJSONArray(TAG_RESULTS);

            for(int i=0;i<peoples.length();i++){
                JSONObject c = peoples.getJSONObject(i);
                String name = c.getString(TAG_NAME);
                String age = c.getString(TAG_AGE);
                String sex = c.getString(TAG_SEX);

                HashMap<String,String> persons = new HashMap<String,String>();

                persons.put(TAG_NAME,name);
                persons.put(TAG_AGE,age);
                persons.put(TAG_SEX,sex);

                personList.add(persons);
            }

            ListAdapter adapter = new SimpleAdapter(
                    MainActivity.this, personList, R.layout.list_item,
                    new String[]{TAG_NAME,TAG_AGE,TAG_SEX},
                    new int[]{R.id.name, R.id.age, R.id.sex}
            );

            list.setAdapter(adapter);

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

    }

    public void getData(){
        class GetDataJSON extends AsyncTask<String, Void, String>{

            @Override
            protected String doInBackground(String... params) {
                DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
                HttpPost httppost = new HttpPost("http://localhost/test/form.php");

                // Depends on your web service
                httppost.setHeader("Content-type", "application/json");

                InputStream inputStream = null;
                String result = null;
                try {
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity entity = response.getEntity();

                    inputStream = entity.getContent();
                    // json is UTF-8 by default
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
                    StringBuilder sb = new StringBuilder();

                    String line = null;
                    while ((line = reader.readLine()) != null)
                    {
                        sb.append(line + "\n");
                    }
                    result = sb.toString();
                } catch (Exception e) {
                    // Oops
                }
                finally {
                    try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
                }
                return result;
            }

            @Override
            protected void onPostExecute(String result){
                myJSON=result;
                showList();
            }
        }
        GetDataJSON g = new GetDataJSON();
        g.execute();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

   /* @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_user) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }*/
}

Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.yashpachisia.fetchjson">
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Logcat window

12-19 17:17:59.353 5132-5132/? D/OpenGLRenderer: Enabling debug mode 0
12-19 17:17:59.353 5132-5132/? D/AndroidRuntime: Shutting down VM
12-19 17:17:59.357 5132-5132/? W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xa6299288)
12-19 17:17:59.357 5132-5132/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                 java.lang.NullPointerException
                                                     at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
                                                     at org.json.JSONTokener.nextValue(JSONTokener.java:94)
                                                     at org.json.JSONObject.<init>(JSONObject.java:154)
                                                     at org.json.JSONObject.<init>(JSONObject.java:171)
                                                     at com.example.yashpachisia.fetchjson.MainActivity.showList(MainActivity.java:56)
                                                     at com.example.yashpachisia.fetchjson.MainActivity$1GetDataJSON.onPostExecute(MainActivity.java:128)
                                                     at com.example.yashpachisia.fetchjson.MainActivity$1GetDataJSON.onPostExecute(MainActivity.java:89)
                                                     at android.os.AsyncTask.finish(AsyncTask.java:631)
                                                     at android.os.AsyncTask.access$600(AsyncTask.java:177)
                                                     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
                                                     at android.os.Handler.dispatchMessage(Handler.java:99)
                                                     at android.os.Looper.loop(Looper.java:137)
                                                     at android.app.ActivityThread.main(ActivityThread.java:4745)
                                                     at java.lang.reflect.Method.invokeNative(Native Method)
                                                     at java.lang.reflect.Method.invoke(Method.java:511)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
                                                     at dalvik.system.NativeStart.main(Native Method)
Mauker
  • 11,237
  • 7
  • 58
  • 76
Taurus
  • 19
  • 5
  • In which line throw NullPointException – Bahramdun Adil Dec 19 '15 at 17:25
  • I dont know whats causing the exception in this code. – Taurus Dec 19 '15 at 17:48
  • while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } result = sb.toString(); } catch (Exception e) { // Oops } finally { try{if(inputStream != null)inputStream.close();}catch(Exception squish){} } return result; – Taurus Dec 19 '15 at 17:48
  • could you show your JSON response for us ? or maybe tell witch line is the 56 in the method ShowList(). But it looks like your are trying to access something in your JSON that does not exist. – Clayton Oliveira Dec 19 '15 at 17:50
  • Set a breakpoint on the line "myJSON=result;" and check whether the result contains valid JSON. If so, set a breakpoint on the line "JSONObject jsonObj = new JSONObject(myJSON);" and check again whether the JSON looks good. Then you will probably know more. – Dabbler Dec 19 '15 at 18:11
  • which is your 116 line number in code??? – Pankaj Dec 19 '15 at 18:19

1 Answers1

0

call this method showList() only after checking the result you get in onPostExecute() is not null or empty

if(result != null && result.length >0 ){
  myJSON=result;
  showList()
}

as your myJson could be empty you are trying to run Json code on it, due to which you are getting NulPointerError

Update

if you are getting the null value it means, that you are not getting the data from the web service or you are calling it wrong.

I saw some mistakes in your code so i wrote you a new one. my code uses commons-io-2.4.jar library but you can always write your own code to see the result

 String chartString = "your url which you want to call"; 
 URL chartURL = new URL(chartString);
 HttpURLConnection chartHttpURLConnection = (HttpURLConnection) chartURL.openConnection();
 chartHttpURLConnection.connect();
 String result = IOUtils.toString(chartHttpURLConnection.getInputStream());
 System.out.println(""+result);

as you are trying to call the local serve though emulator so the IP address would be 10.0.2.2

so your URL which you would be calling is

URL url = new URL(http://10.0.2.2/test/form.php);

have a look at this IP Address for the Emulator

Community
  • 1
  • 1
Pankaj Nimgade
  • 4,529
  • 3
  • 20
  • 30
  • Thank you for the reply.I put the condition and it seems that my json is returning a null value.Can you please tell me why?Here is the screenshot of my page output. http://s15.postimg.org/6kdaep7zf/jsonss.png – Taurus Dec 20 '15 at 12:50
  • @Taurus, the problem is in the data you are getting, the JSON data should be enclosed in **[ ]** which denotes a JSON Array or the data should be in **{ }** which denotes JSON Object, you have to make sure you remove **Form** which you are echoing in the php file – Pankaj Nimgade Dec 21 '15 at 04:11
  • @Taurus, another problem is in your code is the API call you are making. I have updated the answer so you can see it, if you can get result for a API from a web browser it mean it is a Get request not a POST – Pankaj Nimgade Dec 21 '15 at 05:03