0

I am working on to retrieve data from database with select query and where condition = tid, for that i want to know how to pass tid on server in select query. Please give me any solution how to send tid on server and retrieve data from database for specific tid. Thanks.

some code

 new GetHttpResponse(this).execute();

    listCollege .setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
            TextView tasknameOBJ=(TextView)view.findViewById(R.id.taskname);
            TextView taskidOBJ = (TextView)view.findViewById(R.id.tid);
             tid = taskidOBJ.getText().toString();
            taskname = tasknameOBJ.getText().toString();
            Toast.makeText(ListTask.this,"You selected Id is "+tid,Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(ListTask.this,GetSubTask.class);
            startActivity(intent);

            SharedPreferences sharedPreferences = ListTask.this.getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);

            SharedPreferences.Editor editor = sharedPreferences.edit();


            editor.putString(Config.TID_SHARED_PREF, tid);
            editor.putString(Config.TASKNAME_SHARED_PREF, taskname);
            //Saving values to editor
            editor.commit();
        }
    });
}
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
    private Context context;
    String result;
    List<Task> Task_;
    public GetHttpResponse(Context context)
    {
        this.context = context;
    }

    @Override
    protected void onPreExecute()
    {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... arg0)
    {
        HttpService httpService = new HttpService("http://192.168.0.104/GroupBuilder/GetListTask.php");
        try
        {
            httpService.ExecutePostRequest();

            if(httpService.getResponseCode() == 200)
            {
                result = httpService.getResponse();

                System.out.println("Result       . . . "+result);

                Log.d("Result", result);
                if(result != null)
                {
                    JSONArray jsonArray = null;
                    try {
                        jsonArray = new JSONArray(result);

                        JSONObject object;
                        JSONArray array;
                        Task_ = new ArrayList<Task>();
                        for(int i=0; i<jsonArray.length(); i++)
                        {
                            task_ = new Task();
                            object = jsonArray.getJSONObject(i);

                            task_.taskname = object.getString("taskname");
                            task_.tid = object.getString("tid");

                            System.out.println("Taask Tid  "+task_.tid);
                            Task_.add(task_);
                        }
                    }
                    catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
            else
            {
                Toast.makeText(context, httpService.getErrorMessage(), Toast.LENGTH_SHORT).show();
            }
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result)

    {
        proCollageList.setVisibility(View.GONE);
        listCollege.setVisibility(View.VISIBLE);
        if(Task_ != null)
        {
            ListTaskAdapter adapter = new ListTaskAdapter(Task_, context);
            listCollege.setAdapter(adapter);
        }
    }
}//

public class HttpService
{

    private ArrayList <NameValuePair> params;
    private ArrayList <NameValuePair> headers;

    private String url;
    private int responseCode;
    private String message;
    private String response;

    public String getResponse()
    {
        return response;
    }

    public String getErrorMessage()
    {
        return message;
    }

    public int getResponseCode()
    {
        return responseCode;
    }

    public HttpService(String url)
    {
        this.url = url;
        params = new ArrayList<NameValuePair>();
        headers = new ArrayList<NameValuePair>();
    }

    public void AddParam(String name, String value)
    {
        params.add(new BasicNameValuePair(name, value));
    }

    public void AddHeader(String name, String value)
    {
        headers.add(new BasicNameValuePair(name, value));
    }


    public void ExecutePostRequest() throws Exception
    {
        HttpPost request = new HttpPost(url);
        for(NameValuePair h : headers)
        {
            request.addHeader(h.getName(), h.getValue());
        }

        if(!params.isEmpty())
        {
            request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
        }

        executeRequest(request, url);
    }

    private void executeRequest(HttpUriRequest request, String url)
    {
        HttpParams httpParameters = new BasicHttpParams();
        int timeoutConnection = 10000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        int timeoutSocket = 10000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

        HttpClient client = new DefaultHttpClient(httpParameters);
        HttpResponse httpResponse;
        try
        {
            httpResponse = client.execute(request);
            responseCode = httpResponse.getStatusLine().getStatusCode();
            message = httpResponse.getStatusLine().getReasonPhrase();

            HttpEntity entity = httpResponse.getEntity();
            if (entity != null)
            {
                InputStream instream = entity.getContent();
                response = convertStreamToString(instream);
                instream.close();
            }
        }
        catch (ClientProtocolException e)
        {
            client.getConnectionManager().shutdown();
            e.printStackTrace();
        }
        catch (IOException e)
        {
            client.getConnectionManager().shutdown();
            e.printStackTrace();
        }
    }

    private String convertStreamToString(InputStream is)
    {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try
        {
            while ((line = reader.readLine()) != null)
            {
                sb.append(line + "\n");
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                is.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

Thank You so much.

  • you just have to use the AddParam in your HttpService – Mr.Popular May 08 '17 at 04:21
  • please can you explain in detail , i am new in android. Thank you so much for reply – Manoj Gayakwad May 08 '17 at 04:27
  • 1
    @ManojGayakwad Check this answer, http://stackoverflow.com/questions/3288823/how-to-add-parameters-in-android-http-post it contains solution to your question with sample code. Also I will suggest to use Retrofit or volley for making network calls, these libraries are very easy to use – Arshad May 08 '17 at 04:36
  • public void AddParam(String name, String value) { params.add(new BasicNameValuePair(name, value)); } use this method man.... after creating object to httpservice just add ur id by calling the addParam("id", YOURID); THATS ALL – Mr.Popular May 08 '17 at 04:38
  • @Mr.Popular I have already AddParam method .I add that one , but i dont understand how to add my id and where to have declare. please give me solution or edit my code. Thanks – Manoj Gayakwad May 08 '17 at 05:09
  • I added code into Addparam, But I am not getting how to send Id to the server. – Manoj Gayakwad May 08 '17 at 07:51

1 Answers1

0
 public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
                                  List<NameValuePair> params) {

    // Making HTTP request
    try {

        // check for request method
        if(method == "POST"){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

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

        }else if(method == "GET"){
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }

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

    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");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}
}

in your app dependency

   dependencies{
compile 'httpclient-4.2.3.jar'
compile 'apache-httpcomponents-httpcore1.jar'
} 

(i dont know the correct name just search for the jar files in android studio surely it ll be there.. find it and add it to your dependency and compile then only some methods in it will work) and in your activity

   public class MyActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my);
    new Async().execute();
}

class Async extends AsyncTask<String,String,String>{

    @Override
    protected String doInBackground(String... strings) {
        JSONParser parser = new JSONParser();
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("id", "1234"));
        JSONObject obj = parser.makeHttpRequest("http://192.168.0.43/myproject/test.php", "GET", params);
        System.out.println(obj.toString());

        return null;
    }
}
 }

and in your php side

 <?php
   $con = mysql_connect("localhost", "username", "password");
    $re = mysql_select_db("db_name", $con);

 $responce = array();
  $name = $_REQUEST['id'];

 $query = "select ...";
 $result = mysql_query($query, $con);
 $row = mysql_fetch_row($result);

 $responce["value"] = array();
 $data = array();
  $data["name"] = $row["name"];
    (something like that)
   array_push($responce["value"] , $data);

  echo json_encode($responce);

  ?>
Mr.Popular
  • 845
  • 1
  • 8
  • 15