0

this is my code for getting data from a PHP site into a ListView.

package be.pressd.arrangementen;

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

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{
    Button fetch;
    EditText et;
    String aantalPersonen; 

    private ListView lv;  
    private ArrayAdapter<String> listAdapter ; 

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

        fetch = (Button) findViewById(R.id.fetchButton);
        et = (EditText) findViewById(R.id.aantalPersonen);

        // Find the ListView resource.     
        lv = (ListView) findViewById(R.id.arrangementenLijst);   
        listAdapter = new ArrayAdapter<String>(this, R.layout.line_row);  

        lv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //Toast.makeText(getApplicationContext(), "Click nummer " + position, Toast.LENGTH_LONG).show();
                String arrangement = (String) lv.getItemAtPosition(position);

                // Launching new Activity on selecting single List Item
                Intent i = new Intent(getApplicationContext(), ArrangementItem.class);

                // sending data to new activity
                i.putExtra("arrangement", arrangement);
                startActivity(i);
            }

        });

        fetch.setOnClickListener(this);
    }

    class task extends AsyncTask<String, String, Void>
    {
        private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
        InputStream is = null ;
        String result = "";


        protected void onPreExecute() {
            progressDialog.setMessage("Fetching data...");
            progressDialog.show();
            progressDialog.setOnCancelListener(new OnCancelListener() {

                @Override
                public void onCancel(DialogInterface arg0) {
                    task.this.cancel(true);
                }
            });
        }

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

            String url_select = "http://mywebsite/thephpform.php?aantpers=" + aantalPersonen;

            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url_select);

            ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();

            try 
            {
                httpPost.setEntity(new UrlEncodedFormEntity(param));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();

                //read content
                is =  httpEntity.getContent();                  

            } catch (Exception e) {

                Log.e("log_tag", "Error in http connection "+e.toString());
            }

            try {
                BufferedReader br = new BufferedReader(new InputStreamReader(is));
                StringBuilder sb = new StringBuilder();

                String line = "";

                while((line=br.readLine())!=null)
                {
                    sb.append(line+"\n");
                }

                is.close();
                result=sb.toString();               

            } catch (Exception e) {

                Log.e("log_tag", "Error converting result "+e.toString());
            }
            return null;
        }

        protected void onPostExecute(Void v) {

            try 
            {   listAdapter.clear();
                JSONArray Jarray = new JSONArray(result);

                for(int i=0; i < Jarray.length(); i++)
                {
                    JSONObject Jasonobject = null;
                    Jasonobject = Jarray.getJSONObject(i);

                    String name = Jasonobject.getString("naam");

                    listAdapter.add(name);
                }
                this.progressDialog.dismiss();

                lv.setAdapter( listAdapter);

            } catch (Exception e) {

                Log.e("log_tag", "Error parsing data "+e.toString());
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()) {
            case R.id.fetchButton :

                aantalPersonen = et.getText().toString();
                if (aantalPersonen.trim().equals("")) {
                    Toast.makeText(this, "Gelieve het aantal personen in te geven", Toast.LENGTH_SHORT).show();
                    return;
                }
                else 
                {
                        new task().execute();
                        break;
                }       
        }
    }
}

It is my first Android code ever, so besides my question it is possible that this code can be made better.

What I would like to do is to show ALL data, nicely, which was gotten from the website. But, as a ListView can not contain the ID and other data, I'm wondering if I can reuse the data in the JSONObject to be shown in next screen (on click of ListView item) ?

Greetings and thanks in advance,

Davy

Davy
  • 15
  • 1
  • 7
  • save data in shared pref or some static variable to persist the data – KOTIOS Aug 13 '14 at 09:39
  • Save data in arraylist or hashmap – Vijay Barbhaya Aug 13 '14 at 10:05
  • @user Are you getting the answer? – Paritosh Aug 13 '14 at 11:48
  • Is your problem solved ? You got any answer ? – Paritosh Aug 14 '14 at 12:46
  • Paritosh, I tried the answer from Deep Shah, but see in one of the answers what is happening now. The solution code you gave was about exactly the same as what I had in my code... – Davy Aug 14 '14 at 20:08
  • I'm trying to understand all answers, will need some time to discover... Will do some tests, although I'm not sure yet what shared pref or hashmaps are. Static variables seem to be able to do the task, but if I read 20 items from the MySQL database, with 5 keys per item, I'd need 100 variables ? – Davy Aug 14 '14 at 20:31
  • BTW, about the amount of data : I'm reading a MySQL table with (currently) 11 lines, containing 8 variables each, of which two are "text", so containing text, links, ... These are NOT user preferences but a lookup of data from a company – Davy Aug 14 '14 at 20:32

3 Answers3

0

You could

  • save the JSON and parse it again later (you would have to do a lot of parsing)
  • save the data you parse from the json
    • in sharedpreferences (only if small amount of data)
    • in a local sqlite db (probably cleanest approach with best user experience, but a lot of work since you have to create a class that does all the db CRUD operations)

It depends on your data. For user preferences I would use SharedPreferences, for larger amounts a local DB. Also you could create some objects to store the data you need, maybe as signletons or something, and parse the stored JSONs everytime you start the app.

See the google docs on data storage for reference.

tritop
  • 1,655
  • 2
  • 18
  • 30
0

Create variables for which you want to store information and loop through JsonArray and get each JsonObject and parse/extract information that you need and store it in variables.

here is sample code to iterate JsonArray //Here response is JsonArray

Create Simple class like

 public class PersonInfo{

   String name,address; //Create variables of your requirement.


   //Add Getter Setter Methods for these variables

  }

//End of class PersonInfo

  ArrayList<PersonInfo> persons = new ArrayList<PersonInfo>();
  PersonInfo person;
  JSONObject product;


  try
   {
      for (int j = 0; j < response.length(); j++)
       {
          person = new Person();


          product = response.getJSONObject(j);

          person.name =  product.getString("JSON_KEY_NAME"); //like these assign values to each variable of PersonInfo class
          //Other values initialization
       }

     persons.add(person); // Add PersonInfo object to ArrayList        

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

something like that .

you can get json values upon your requirments. This is just sample code .

Deep Shah
  • 1,334
  • 3
  • 20
  • 41
  • If I would run this code, it would mean I need to make 8 different arrays as I have 8 fields that are read from the database ? – Davy Aug 13 '14 at 20:14
  • for that just create bean class that holds that 8 variables and create object of that class and assign value to each variable and add it to one ArrayList i.e ArrayList. – Deep Shah Aug 14 '14 at 03:37
  • Wow, sorry, no idea what you're talking about "bean class" ?? Not that far in Java dev yet... :-( – Davy Aug 14 '14 at 20:08
  • I have added the code : In the class MainActivity, added three lines: ' String[] arrangementNamen; String[] minimumPersonen; String[] maximumPersonen;' In onPostExecute I added this : ' String[] arrangementNamen = new String[Jarray.length()]; String[] minimumPersonen = new String[Jarray.length()]; String name = Jasonobject.getString("naam"); arrangementNamen[i] = name; String minpers = Jasonobject.getString("minpers"); minimumPersonen[i] = minpers; ' In my onItemClick I added ' i.putExtra("minimumPersonen", minimumPersonen[position]);' Unfortunately I get an error... – Davy Aug 14 '14 at 20:33
-1

To save data you are getting in background task you have to use shared preferences.

Refer this link to get details about shared preferences.

To pass data to next page you have to use following code :

Intent intent = new Intent( currentActivity.this, NextActivity.class);
intent.putExtra("key", "value");
startActivity(intent);

On nextActivity.java add following code inside onCreate()

Intent currentPageIntent = getIntent();
String strValue = currentPageIntent.getStringExtra("key");

If you are having any other data type than string you have to use other method instead of getStringExtra()

To get id of item clicked, you can use following code :

list.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            try {
                JSONArray jsonArray = new JSONArray(jsonData);                  

                if (jsonArray != null) {
                    for (int i = 0; i < jsonArray.length(); i++) {
                        if (i == id) {
                            //Add your code here
                        }
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally { }
        }
    });

Note that you have to process jsonData on your own. This is just sample code I used in one of my porjects.

Community
  • 1
  • 1
Paritosh
  • 2,097
  • 3
  • 30
  • 42
  • This is in fact the same as what I'm doing in my code... My problem is more in the fact of having the other fields and data available when clicking the item in the ListView. – Davy Aug 13 '14 at 20:13