-1

I'm unable to retrieve the data from MySQL database to the app. When I click on the button to show the data, the activity closes itself and goes to main activity.

public class Cohorts extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_cohorts);

    String result = null;
    InputStream is = null;
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://website/new/db_connect.php");
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

        Log.e("log_tag", "connection success");
        //   Toast.makeText(getApplicationContext(), “pass”, Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection" + e.toString());
        Toast.makeText(getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show();

    }
    //convert response to string
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
            //  Toast.makeText(getApplicationContext(), “Input Reading pass”, Toast.LENGTH_SHORT).show();
        }
        is.close();

        result = sb.toString();
    } catch (Exception e) {
        Log.e("log_tag", "Error converting result" + e.toString());
        Toast.makeText(getApplicationContext(), "Input reading fail", Toast.LENGTH_SHORT).show();

    }

    //parse json data
    try {
        JSONArray jArray = new JSONArray(result);
        TableLayout tv = (TableLayout) findViewById(R.id.table);
        tv.removeAllViewsInLayout();
        int flag = 1;
        for (int i = -1; i < jArray.length() - 1; i++) {
            TableRow tr = new TableRow(Cohorts.this);
            tr.setLayoutParams(new LayoutParams(
                    LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT));
            if (flag == 1) {
                TextView b6 = new TextView(Cohorts.this);
                b6.setText("Cohort Id");
                b6.setTextColor(Color.BLUE);
                b6.setTextSize(15);
                tr.addView(b6);
                TextView b19 = new TextView(Cohorts.this);
                b19.setPadding(10, 0, 0, 0);
                b19.setTextSize(15);
                b19.setText("Cohort Name");
                b19.setTextColor(Color.BLUE);
                tr.addView(b19);
                TextView b29 = new TextView(Cohorts.this);
                b29.setPadding(10, 0, 0, 0);
                b29.setText("Cohort Leader");
                b29.setTextColor(Color.BLUE);
                b29.setTextSize(15);
                tr.addView(b29);
                TextView b30 = new TextView(Cohorts.this);
                b30.setText("Certified Leader");
                b30.setTextColor(Color.BLUE);
                b30.setTextSize(15);
                tr.addView(b30);
                TextView b35 = new TextView(Cohorts.this);
                b35.setText("Associate Faculty");
                b35.setTextColor(Color.BLUE);
                b35.setTextSize(15);
                tr.addView(b35);
                TextView b39 = new TextView(Cohorts.this);
                b39.setText("Cohort Location");
                b39.setTextColor(Color.BLUE);
                b39.setTextSize(15);
                tr.addView(b39);
                tv.addView(tr);
                final View vline = new View(Cohorts.this);
                vline.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, 2));
                vline.setBackgroundColor(Color.BLUE);
                tv.addView(vline);
                flag = 0;
            } else {
                JSONObject json_data = jArray.getJSONObject(i);
                Log.i("log_tag", "Cohort ID: " + json_data.getInt("Cohort_ID") + ", Cohort Name: " + json_data.getString("Cohort_Name") + ", Cohort Leader" + json_data.getString("Cohort_Leader") + ", Certified Leader: " + json_data.getString("Certified_Leader") + ", Associate Faculty" + json_data.getString("Associate_Faculty") + ", Cohort Location" + json_data.getString("Cohort_Location"));
                TextView b = new TextView(Cohorts.this);
                String stime = String.valueOf(json_data.getInt("Cohort_ID"));
                b.setText(stime);
                b.setTextColor(Color.RED);
                b.setTextSize(15);
                tr.addView(b);
                TextView b1 = new TextView(Cohorts.this);
                b1.setPadding(10, 0, 0, 0);
                b1.setTextSize(15);
                String stime1 = json_data.getString("Cohort_Name");
                b1.setText(stime1);
                b1.setTextColor(Color.BLACK);
                tr.addView(b1);
                TextView b2 = new TextView(Cohorts.this);
                b2.setPadding(10, 0, 0, 0);
                String stime2 = json_data.getString("Cohort_Leader");
                b2.setText(stime2);
                b2.setTextColor(Color.BLACK);
                b2.setTextSize(15);
                tr.addView(b2);
                TextView b3 = new TextView(Cohorts.this);
                String stime3 = String.valueOf(json_data.getInt("Certified_Leader"));
                b3.setText(stime3);
                b3.setTextColor(Color.BLACK);
                b3.setTextSize(15);
                tr.addView(b3);
                TextView b4 = new TextView(Cohorts.this);
                b4.setPadding(10, 0, 0, 0);
                b4.setTextSize(15);
                String stime4 = json_data.getString("Associate_Faculty");
                b4.setText(stime4);
                b4.setTextColor(Color.BLACK);
                tr.addView(b4);
                TextView b5 = new TextView(Cohorts.this);
                b5.setPadding(10, 0, 0, 0);
                String stime5 = json_data.getString("Cohort_Location");
                b5.setText(stime5);
                b5.setTextColor(Color.BLACK);
                b5.setTextSize(15);
                tr.addView(b5);
                tv.addView(tr);
                final View vline1 = new View(Cohorts.this);
                vline1.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, 1));
                vline1.setBackgroundColor(Color.WHITE);
                tv.addView(vline1);
            }
        }
    } catch (JSONException e) {
        Log.e("log_tag", "Error parsing data" + e.toString());
        Toast.makeText(getApplicationContext(), "JsonArray fail", Toast.LENGTH_SHORT).show();
    }
}

}

Manish Dubey
  • 4,206
  • 8
  • 36
  • 65
rijo raju
  • 69
  • 1
  • 1
  • 7

3 Answers3

0

I am sure you are getting NetworkOperationOnMainThread Exception; use async task for that. And take care of updating UI in OnPostexecute() method.

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

    ProgressDialog pd = null;


    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();

        pd = new ProgressDialog(your_activity.this);
        pd.setTitle("Creating Backup");
        pd.setMessage("processing.....");
        pd.show();
    }

    @Override
    protected Void doInBackground(Void... arg0) {
        // TODO Auto-generated method stub

        // execute operation here

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
    if(pd != null){
                pd.dismiss();
    }
    // update UI
}
SRB Bans
  • 3,096
  • 1
  • 10
  • 21
0

You are making network request on Main UI Thread. So you are getting NetworkONMainThreadException(See logcat) and your activity exits. Use Asynctask for this purpose which will work as background worker thread and send resulted data to UI thread. Below is example of Asynctask implementation.

class TestAsync extends AsyncTask<Void, Integer, String>
{
    protected void onPreExecute (){
        Log.d("PreExceute","On pre Exceute......");
    }

    protected String doInBackground(Void...arg0) {
        Log.d("DoINBackGround","On doInBackground...");
        // Do your HTTP network request code here
        return "You are at PostExecute";
    }

    protected void onPostExecute(String result) {
        // Update all UI widgets values here
        Log.d(""+result);
    }
}

Call it like this in your activity:

new TestAsync().execute();

Instead of Asynctask You can use other third-party library from Github. Some of them, I like are Retrofit and Volley. I am sharing my Github repo URL for implementing Retrofit in your Android app for making network request.

Retrofit Android Example

Volley Implementation

Community
  • 1
  • 1
Manish Dubey
  • 4,206
  • 8
  • 36
  • 65
  • thanks for your reply...as i said im new to android..could you just help me to do it...can you tell me how to do it exactly...i really dont know thats why – rijo raju Sep 09 '15 at 08:43
0

No need to use even Async task, use google's own volley library. Download it from here and import it as a module in your application. This is the most modular approach. Volley will itself take care of the background work

Kaveesh Kanwal
  • 1,753
  • 17
  • 16