Tan
Tan

Reputation: 11

Add ItemOnClick from my listview, fetching data using JSON from MYSQL

I'm a beginner to android development. It may look very basic but i really getting a hard-time to make it work in my project.

I am developing an application for professor to see all the student list who under probation in database.

in my progress after they log in their account to the application, all the students who are in the database will show in ListView form

here is my code for this activity

UPDATE1:I Manage to make the items clickable and show new activity named Profile.class (i expect it to show student name: show name student id: show id but it showing NULL)

Here is my update code

public class MainPage extends Activity {

TextView name,email;
private String jsonResult;
private String url = "http://192.168.254.106/notificationapp/students.php";
private ListView listView;
String stud_name, stud_id;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mainpage_layout);
    name = (TextView)findViewById(R.id.name);
    email = (TextView)findViewById(R.id.email);
    Bundle bundle = getIntent().getExtras();
    name.setText("Welcome "+bundle.getString("name"));
    email.setText("Email: "+bundle.getString("email"));
    listView = (ListView) findViewById(R.id.listView);
    accessWebService();
}



@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;
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... params) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(params[0]);
        try {
            HttpResponse response = httpclient.execute(httppost);
            jsonResult = inputStreamToString(
                    response.getEntity().getContent()).toString();
        }

        catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    private StringBuilder inputStreamToString(InputStream is) {
        String rLine = "";
        StringBuilder answer = new StringBuilder();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));

        try {
            while ((rLine = rd.readLine()) != null) {
                answer.append(rLine);
            }
        }

        catch (IOException e) {
            // e.printStackTrace();
            Toast.makeText(getApplicationContext(),
                    "Error..." + e.toString(), Toast.LENGTH_LONG).show();
        }
        return answer;
    }

    @Override
    protected void onPostExecute(String result) {
        ListDrawer();
    }
}// end async task

public void accessWebService() {
    JsonReadTask task = new JsonReadTask();
    task.execute(new String[] { url });
}


public void ListDrawer() {
    final List<Map<String, String>> studentList = new ArrayList<Map<String, String>>();

    try {
        JSONObject jsonResponse = new JSONObject(jsonResult);
        JSONArray jsonMainNode = jsonResponse.optJSONArray("student_info");

        for (int i = 0; i < jsonMainNode.length(); i++) {
            JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
            String name = jsonChildNode.optString("student_name");
            String number = jsonChildNode.optString("student_id");
            String outPut = name + "-" + number;
            studentList.add(createStudent("Students", outPut));
        }
    } catch (JSONException e) {
        Toast.makeText(getApplicationContext(), "Error" + e.toString(),
                Toast.LENGTH_SHORT).show();
    }
 ////////////////////////////////// UPDATE LISTVIEW ITEMS ONCLICK
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
             studentList.get(position);
            //Do your logic for getting the student variables here
            Intent intent = new Intent(MainPage.this,Profile.class);
            Bundle b = new Bundle();
            b.putString("student_name", stud_name);
            b.putString("student_id", stud_id);
            intent.putExtras(b);
            startActivity(intent);
        }
    });
//////////////////////////////////////UPDATE END
    SimpleAdapter simpleAdapter = new SimpleAdapter(this, studentList,
            android.R.layout.simple_list_item_1,
            new String[] { "Students" }, new int[] { android.R.id.text1 });
    listView.setAdapter(simpleAdapter);
    Toast.makeText(getApplication(), "Logged in Successfully", Toast.LENGTH_SHORT).show();

}

private HashMap<String, String> createStudent(String name, String number) {
    HashMap<String, String> Students = new HashMap<String, String>();
    Students.put(name, number);
    return Students;
}

}

MY Profile Activity

public class Profile extends Activity {

TextView stud_name,stud_id;

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

    stud_name = (TextView)findViewById(R.id.student_name);
    stud_id = (TextView)findViewById(R.id.student_id);
    Bundle bundle = getIntent().getExtras();
    stud_name.setText("Student name: "+bundle.getString("student_name"));
    stud_id.setText("Student ID: "+bundle.getString("student_id"));
}

}

I think my problem is in my php how do i configure this if im using the bundle method? to get the string data from mysql and send it to Profile activity after i click one item from ListView?

<?php
$host="localhost";
$username="thesis"; 
$password="thesis123"; 
$db_name="professor_db";
$con=mysql_connect("$host", "$username", "$password")or die("cannot      connect"); 
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "select * from student_info"; 
$result = mysql_query($sql);
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_assoc($result)){
$json['student_info'][]=$row;
}
}
mysql_close($con);
echo json_encode($json); 
?>    

Upvotes: 1

Views: 131

Answers (3)

Sagar Thakarar
Sagar Thakarar

Reputation: 271

You can create a class for all basic and common information of students available with you, create its get() & set() methods. The data you are geting from json store it using it's set() methods like :

public class StudentInfo{
    public String stud_name, stud_id ,stud_roll_num ,stud_add;

    // get Student Name with this method
    public String getName() {
        return stud_name;
    }

    // set Student Name with this method
    public void setName(String name) {
        this.stud_name = name;
    }

    public String getRollNum() {
        return stud_roll_num;
    }

    public void setRollNum(String rollNum) {
        this.stud_roll_num = rollNum;
    }
}

Then use it like this :

 public ArraryList<StudentInfo> studinfo = new ArraryList<StudentInfo>();

 String name = studinfo.get(position).stud_name;
 String roll_num = studinfo.get(position).stud_roll_num;

Upvotes: 0

babadaba
babadaba

Reputation: 814

You can set an onItemClickListener on your ListView. In the onClick method you get the student from your array depending on the selected position. With that data you create an Intent with extras and start it. Example:

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            ... studentList.get(position); //Do your logic for getting the student variables here

            Intent intent = new Intent(MainPage.this, TargetActivity.class);
            intent.putExtra("name", studentName);
            intent.putExtra("id", studentId);
            startActivity(intent);
        }
});

In your TargetActivity (or what ever its called in your project) add this in your onCreate method:

Intent intent = getIntent();
String studentName = intent.getStringExtra("name");
int studentId = intent.getIntExtra("id",-1);

Upvotes: 1

Vishal
Vishal

Reputation: 537

You can create a customListView attach clickListener to each element of the listview, clickListener will take you to the other activity through INTENT, you can also send some data with the INTENT on basis of which your new activity will be populated.

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class CustomAdapter extends BaseAdapter{   
    String [] result;
    Context context;
 int [] imageId;
      private static LayoutInflater inflater=null;
    public CustomAdapter(MainActivity mainActivity, String[] prgmNameList, int[] prgmImages) {
        // TODO Auto-generated constructor stub
        result=prgmNameList;
        context=mainActivity;
        imageId=prgmImages;
         inflater = ( LayoutInflater )context.
                 getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return result.length;
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    public class Holder
    {
        TextView tv;
        ImageView img;
    }
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        Holder holder=new Holder();
        View rowView;       
             rowView = inflater.inflate(R.layout.program_list, null);
             holder.tv=(TextView) rowView.findViewById(R.id.textView1);
             holder.img=(ImageView) rowView.findViewById(R.id.imageView1);       
         holder.tv.setText(result[position]);
         holder.img.setImageResource(imageId[position]);         
         rowView.setOnClickListener(new OnClickListener() {            
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Toast.makeText(context, "You Clicked "+result[position], Toast.LENGTH_LONG).show();
            }
        });   
        return rowView;
    }

} 

https://www.caveofprogramming.com/guest-posts/custom-listview-with-imageview-and-textview-in-android.html

Upvotes: 1

Related Questions