1

I'm a new programmer and I'm making an app which can get data from MYSQL to php and then display on android. I've been trying to find a solution but none of the tutorials I've seen so far seems to work for me, I've only managed to get one object from json into a single textview. But what I really need is to get data to be displayed on individual rows on listview.

here's my JSON output,

 [{"id":"1","name":"darrel","password":"pass1234"},{"id":"2","name":"garrett","password":"important"},{"id":"3","name":"neoys","password":"yseniopass"},{"id":"4","name":"john","password":"mikel123"},{"id":"5","name":"owen","password":"mike4l"}]

and my java code which gets only one of the users displayed onto a textview.

  package com.darre.jsonreader;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ListActivity;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public class Users extends ListActivity {


    /** Called when the activity is first created. */

    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    @SuppressLint("NewApi")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        //listView.setOnItemClickListener(new OnItemClickListener() {
        //  public void onItemClick(AdapterView<?> parent, View view,
        //          int position, long id) {
                // When clicked, show a toast with the TextView text
        //      Toast.makeText(getApplicationContext(),
            //  ((TextView) view).getText(), Toast.LENGTH_SHORT).show();


        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);

        }
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://172.30.54.153/databases/");
        TextView textView = (TextView)findViewById(R.id.textView1);

        ListView listview = (ListView)findViewById(R.id.listView1);
  try {

   HttpResponse response = httpclient.execute(httppost);
   String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
   JSONArray mArray = new JSONArray(jsonResult);
   for (int i = 0; i < mArray.length(); i++) {
       JSONObject object = mArray.getJSONObject(i);




      String name = object.getString("name");
     String password = object.getString("password");
      textView.setText(name + " - " + password);

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



       }

Thanks in advance!!!

Darrel
  • 56
  • 1
  • 2
  • 8
  • use a custom listview. http://stackoverflow.com/questions/10816243/search-in-listview-with-edittext/15367403#15367403. Just add json data in the for loop. – Raghunandan Mar 22 '13 at 08:02
  • I recommend the following blog post. It talks about ListActivity and JSONObjects: http://www.androidhive.info/2012/01/android-json-parsing-tutorial/ – IgorGanapolsky Sep 24 '13 at 20:25

3 Answers3

0

If you want to use a ListView... then you should parse you JSON file into some kind of data structure like a List or an ArrayList and the n use an adapter to populate the ListView data.

Here is an example for ListView adapter:

    private class MySecondAdapter extends ArrayAdapter<MiniTask>
{   
    private ArrayList<MiniTask> list;

    public MySecondAdapter(Context context, int textViewResourceId, ArrayList<MiniTask> miniTaskList) 
    {
        super(context, textViewResourceId, miniTaskList);
         this.list = new ArrayList<MiniTask>();
         this.list.addAll(miniTaskList);
    }

    public View getView(final int position, View convertView, ViewGroup parent)
    {
        miniTask = miniTaskList.get(position);
        ViewHolder holder = new ViewHolder();
        {
            LayoutInflater inflator = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflator.inflate(R.layout.check_list_item_new, null);

            holder.title = (TextView) convertView.findViewById(R.id.tvItemTitle);
            holder.commentsPicturesButton = (ImageView) convertView.findViewById(R.id.iAddCommetOrPicture);
            holder.commentsPicturesButton.setTag(position);
            holder.commentsPicturesButton.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) 
                {
                     Intent intent = new Intent(getApplicationContext(), PicturesAndCommentsActivity.class);
                     intent.putExtra(TasksListActivity.KEY_ID, task.getId());
                     intent.putExtra("mini_task_text", miniTask.getTitle());
                     startActivity(intent);
                }
            });
            holder.selected = (CheckBox) convertView.findViewById(R.id.cbCheckListItem);
            holder.selected.setTag(position);
            holder.selected.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v)
                {    
                    {                               
                        Log.d(TAG, "pressed the checkbox: " + v.getId() + " in position: " + position + " tag: " +v.getTag() +" and item from array: " + miniTaskList.get(position) );
                        CheckBox checkbox = (CheckBox) v;
                        miniTaskList.get(position).setSelected(checkbox.isChecked());   
                        numOfCheckedMiniTasks = 0;
                        for(int i=0;i<miniTaskList.size();i++)
                        {
                             miniTask = miniTaskList.get(i);
                             if(miniTask.isSelected())
                             {
                                numOfCheckedMiniTasks ++;
                             }
                        }
                        int percent = (int)(numOfCheckedMiniTasks * 100.0f) / miniTaskList.size();
                        Log.d(TAG, "the percentage is: " +percent);
                        tasksRepository.get(tasksRepository.indexOf(task)).setMiniTasksPercentageComplete(percent);
                    }
                }
            });
        }

        holder.title.setText(miniTask.getTitle());
        holder.selected.setChecked(miniTask.isSelected());
        return convertView;
    }
}

Check this tutorials for getting more information:

http://cyrilmottier.com/2012/02/16/listview-tips-tricks-5-enlarged-touchable-areas/

Emil Adz
  • 40,709
  • 36
  • 140
  • 187
0

You have to create ListView adapter:

Put this in your Code :

private String[] listArr;
public ArrayList<String> ary_name = new ArrayList<String>();

try {

   HttpResponse response = httpclient.execute(httppost);
   String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
   JSONArray mArray = new JSONArray(jsonResult);
   for (int i = 0; i < mArray.length(); i++) {
       JSONObject object = mArray.getJSONObject(i);




      String name = object.getString("name");
     String password = object.getString("password");
      textView.setText(name + " - " + password);

    ary_name.add(name);

  }


    listArr = new String[ary_name.size()];
    listArr = ary_name.toArray(listArr);



MyArrayAdapter adapter = new MyArrayAdapter(this, listArr);
        listView.setAdapter(adapter);



public class MyArrayAdapter extends ArrayAdapter<String> {

        Activity context;
        String[] listArr;

        private TextView btnchkout;

        // private final integer[] image;

        public MyArrayAdapter(Activity context, String[] objects) {
            super(context, R.layout.custmlayout, objects);
            // TODO Auto-generated constructor stub
            this.context = context;
            listArr = objects;

        }

        @Override
        public View getView(final int position, View convertView,
                ViewGroup parent) {
            // TODO Auto-generated method stub


            LayoutInflater inflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
            View view = inflater.inflate(R.layout.custmlayout, null, true);

            TextView textView = (TextView) view.findViewById(R.id.txtTicketNo);
            textView.setText(listArr[position]);

            return view;
        }
    }
Nirav Ranpara
  • 13,753
  • 3
  • 39
  • 54
0

You can read this tutorial, it explains to ways of implement it, the first, a "direct" List adapter, the second, the way to customize your List.

http://www.mkyong.com/android/android-listview-example/

Also, you shouldn't work with JSON data, first, you have to create an Object for each Item, and then group it with some kind of List (ArrayList, for example).

Ger Soto
  • 328
  • 2
  • 12
  • Please include the relevant parts of the page you are linking to in the answer. If the site you link to goes down then your answer will become useless. – ChrisF Mar 22 '13 at 10:24
  • Thank you for your suggest, ChrisF, but, I think that this kind of question or topic needs a better explanation than an excerpt of code. That's why I pasted a link to a tutorial and I don´t know what part of this tutorial is the most relevant. I think that my answer could be improved with a resume, but not with an underlinement. – Ger Soto Mar 25 '13 at 14:20