klisfer
klisfer

Reputation: 37

JSON parsing from database

I am trying to parse JSON from one of my json created but I am unable to parse it an throws a null pointer exception at the showdata() method. what is it that i am missing.I have checked with the array name and the php script. How do I implement it to solve the problem

parse activity

 import android.content.Intent;
    import android.support.v7.app.ActionBarActivity;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;

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


    public class ParseJSON extends ActionBarActivity implements View.OnClickListener {
        private String myJSONString;

        private static final String JSON_ARRAY="result";
        private static final String ID = "id";
        //private static final String NAME ="name";
        //private static final String PROFESSION= "profession";

        private JSONArray users = null;

        private int TRACK= 0;

        private EditText editTextId;
        private EditText editTextName;
        private EditText editTextProf;

        Button btnPrev;
        Button btnNext;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_parse_json);

            Intent intent =getIntent();
            myJSONString = intent.getStringExtra(MainActivity.MY_JSON);


            editTextId = (EditText)findViewById(R.id.editTextID);
            //editTextName=(EditText)findViewById(R.id.editTextUsername);
            //editTextProf=(EditText)findViewById(R.id.editTextPassword);

            btnNext=(Button)findViewById(R.id.buttonNext);
            btnPrev=(Button)findViewById(R.id.buttonPrev);

            btnPrev.setOnClickListener(this);
            btnNext.setOnClickListener(this);

            extractJSON();
             showData();

        }



        private void extractJSON() {
            try {
                JSONObject jsonObject = new JSONObject();
                users = jsonObject.getJSONArray(JSON_ARRAY);

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

        }
            private void moveNext(){
           if(TRACK<users.length()){
               TRACK++;
           }
            showData();
        }

        private void movePrev(){
            if(TRACK>0){
                TRACK--;
            }
            showData();
        }

        private void showData(){
          try{
              JSONObject jsonObject= users.getJSONObject(TRACK);

              editTextId.setText(jsonObject.getString(ID));
          //    editTextName.setText(jsonObject.getString(NAME));
            //  editTextProf.setText(jsonObject.getString(PROFESSION));
          }catch(JSONException e){
              e.printStackTrace();
          }
        }
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.menu_parse_json, 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_settings) {
                return true;
            }

            return super.onOptionsItemSelected(item);
        }

        @Override
        public void onClick(View view) {
          if(view==btnNext){
              moveNext();
          }
          else if (view==btnPrev)
              movePrev();
        }
    }

mainactivity

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


public class MainActivity extends ActionBarActivity implements View.OnClickListener {

    private TextView textviewJSON;
    private Button buttonGet;
    private Button buttonParse;


    public static final String MY_JSON="MY_JSON";
    public static final String JSON_URL="http://www.humanfox.com/capsule/dash.php";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textviewJSON=(TextView)findViewById(R.id.textViewJSON);
        textviewJSON.setMovementMethod(new ScrollingMovementMethod());
        buttonGet=(Button)findViewById(R.id.buttonGet);
        buttonParse=(Button)findViewById(R.id.buttonParse);
        buttonGet.setOnClickListener(this);
        buttonParse.setOnClickListener(this);

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.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_settings) {
            return true;
        }


        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View view) {
       if (view==buttonGet){
        getJSON(JSON_URL);

       }
       else if(view==buttonParse){
           showParseActivity();
       }
    }
    private void showParseActivity() {
        Intent intent = new Intent(this, ParseJSON.class);
        intent.putExtra(MY_JSON,textviewJSON.getText().toString());
        startActivity(intent);
    }

    private void getJSON(String url){
        class GetJSON extends AsyncTask<String, Void, String>{
                ProgressDialog loading;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loading= ProgressDialog.show(MainActivity.this, "Please Wait.....",null, true , true);
            }

            @Override
            protected String doInBackground(String... params) {

                String uri=params[0];
                BufferedReader bufferedReader= null;
                try{
                    URL url = new URL(uri);
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    StringBuilder sb = new StringBuilder();

                    bufferedReader= new BufferedReader(new InputStreamReader(con.getInputStream()));

                    String json;
                    while((json= bufferedReader.readLine())!=null){

                        sb.append(json+"\n");

                    }
                    return sb.toString().trim();
                }catch(Exception e){
                    return null;
                }



            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                loading.dismiss();

            }
        }

       GetJSON gj = new GetJSON();
       gj.execute(url);

    }


}

Upvotes: 0

Views: 92

Answers (1)

Pankaj Nimgade
Pankaj Nimgade

Reputation: 4549

I believe the issue is with the way you are trying to iterate through the JSONArray list, try this code it is also available on Github

public class ParseJSONActivity extends AppCompatActivity {

    private Button button;
    private Button previous_Button;
    private Button next_Button;

    private ListView listView;
    private ArrayList<People> peoples;
    private MyAdapter adapter;
    private int TRACK = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_parse_json);
        Toolbar toolbar = (Toolbar) findViewById(R.id.my_custom_toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        initializeUI();
    }

    private void initializeUI() {

        button = (Button) findViewById(R.id.ParseJSONActivity_ok_button);
        previous_Button = (Button) findViewById(R.id.ParseJSONActivity_Previous_button);
        previous_Button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (peoples != null) {
                    if (peoples.size() > 0) {
                        if ((TRACK < peoples.size() - 1) && (TRACK >= 1)) {
                            People people = (People) listView.getItemAtPosition(--TRACK);
                            for (People single_item : peoples) {
                                single_item.setSelected(false);
                            }
                            people.setSelected(true);
                            adapter.notifyDataSetChanged();
                        }else{
                            TRACK = 0;
                        }
                    }
                }
            }
        });
        next_Button = (Button) findViewById(R.id.ParseJSONActivity_next_button);
        next_Button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (peoples != null) {
                    if (peoples.size() > 0) {
                        if (TRACK < peoples.size() - 2) {
                            People people = (People) listView.getItemAtPosition(++TRACK);
                            for (People single_item : peoples) {
                                single_item.setSelected(false);
                            }
                            people.setSelected(true);
                            adapter.notifyDataSetChanged();
                        }else {
                            System.out.println("TRACK: "+TRACK);
                            TRACK = 0;
                        }
                    }
                }else{
                    System.out.println("peoples is null");
                }
            }
        });
        listView = (ListView) findViewById(R.id.ParseJSONActivity_listView);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (peoples != null) {
                    if (peoples.size() > 0) {
                        TRACK = position;
                        People people = (People) listView.getItemAtPosition(position);
                        for (People single_item : peoples) {
                            single_item.setSelected(false);
                        }
                        people.setSelected(true);
                        adapter.notifyDataSetChanged();
                    }
                }
            }
        });

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new DownloadJSON().execute();
            }
        });
    }


    private class DownloadJSON extends AsyncTask<Void, Void, Void> {


        @Override
        protected Void doInBackground(Void... params) {

            try {
                URL url = new URL("http://www.humanfox.com/capsule/dash.php");
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.connect();
                String result = IOUtils.toString(httpURLConnection.getInputStream());
                System.out.println("" + result);
                if (result != null) {
                    JSONObject result_jsonObject = new JSONObject(result);
                    JSONArray result_JsonArray = result_jsonObject.getJSONArray("result");
                    if (result_JsonArray != null) {
                        if (result_JsonArray.length() > 0) {
                            peoples = new ArrayList<>();
                            for (int i = 0; i < result_JsonArray.length(); i++) {
                                People people = new People();
                                JSONObject jsonObject = result_JsonArray.getJSONObject(i);
                                people.setId("" + jsonObject.getString("id"));
                                people.setName("" + jsonObject.getString("Name"));
                                people.setProfession("" + jsonObject.getString("profession"));
                                people.setImage("" + jsonObject.getString("image"));
                                peoples.add(people);
                            }
                        }
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            if (peoples != null) {
                if (peoples.size() > 0) {
                    adapter = new MyAdapter(getApplicationContext(), R.layout.single_item_custom_one, peoples);
                    listView.setAdapter(adapter);
                    adapter.notifyDataSetChanged();
                }
            }
        }
    }

    private class MyAdapter extends ArrayAdapter {

        private ArrayList<People> a_productInfos;
        private Context a_context;
        private LayoutInflater a_layoutInflater;

        public MyAdapter(Context context, int resource, ArrayList<People> a_productInfos) {
            super(context, resource, a_productInfos);
            this.a_productInfos = a_productInfos;
            this.a_context = context;
            a_layoutInflater = LayoutInflater.from(this.a_context);
        }


        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View row = convertView;
            ViewHolder holder = null;
            if (row == null) {
                row = a_layoutInflater.inflate(R.layout.single_item_custom_one, parent, false);
                holder = new ViewHolder();
                holder.product_name = (TextView) row.findViewById(R.id.single_item_custom_one_textView);
                holder.item_LinearLayout = (LinearLayout) row.findViewById(R.id.single_item_custom_one_linearLayout);
                row.setTag(holder);
            } else {
                holder = (ViewHolder) row.getTag();
            }

            final People productInfo = a_productInfos.get(position);
            holder.product_name.setText("" + productInfo.getName());

            if (productInfo.isSelected) {
                holder.item_LinearLayout.setBackgroundColor(Color.parseColor("#ff44ff"));
            } else {
                holder.item_LinearLayout.setBackgroundColor(Color.parseColor("#ffffff"));
            }

            return row;
        }

        class ViewHolder {
            TextView product_name;
            LinearLayout item_LinearLayout;
        }

    }

    private class People {
        private String id;
        private String Name;
        private String profession;
        private String image;
        boolean isSelected;

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getName() {
            return Name;
        }

        public void setName(String name) {
            Name = name;
        }

        public String getProfession() {
            return profession;
        }

        public void setProfession(String profession) {
            this.profession = profession;
        }

        public String getImage() {
            return image;
        }

        public void setImage(String image) {
            this.image = image;
        }

        public boolean isSelected() {
            return isSelected;
        }

        public void setSelected(boolean selected) {
            isSelected = selected;
        }
    }

}

Output:

enter image description here

Upvotes: 1

Related Questions