-1

I am able to read the JSON but now I want to read only some values. I will the id and android should give me the username and password. Or I will give the username and android should provide me the corresponding id and password. Here are my codes:-

Android:-MainActivity.Java

package com.example.nupur.readjsonexample;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


public class MainActivity extends ActionBarActivity implements View.OnClickListener {
    EditText etcheck;

    private TextView textViewJSON;
    private Button buttonGet;
   // TextView txtCheck;
   //private Button buttonParse;

    public static final String MY_JSON ="MY_JSON";

    private static final String JSON_URL = "http://kezinking.com/SampleConLogin1";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       // etcheck=(EditText) findViewById(R.id.etcheck);
       // txtCheck=(TextView) findViewById(R.id.txtCheck);
        textViewJSON = (TextView) findViewById(R.id.textViewJSON);
        textViewJSON.setMovementMethod(new ScrollingMovementMethod());
        buttonGet = (Button) findViewById(R.id.buttonGet);
       // buttonParse = (Button) findViewById(R.id.buttonParse);
        buttonGet.setOnClickListener(this);
       // buttonParse.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        if(v==buttonGet){
            getJSON(JSON_URL);

        }

        //if(v==buttonParse){
          //  showParseActivity();
        //}
    }

    private void showParseActivity() {
        Intent intent = new Intent(this, Showdata.class);
        intent.putExtra(MY_JSON,textViewJSON.getText().toString());
        startActivity(intent);
    }


    private void getJSON(String url) {
        class GetJSON extends AsyncTask<String, Void, String>{
            ProgressDialog loading;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loading = ProgressDialog.show(MainActivity.this, "Please Wait...",null,true,true);
            }

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

                String uri = params[0];

                BufferedReader bufferedReader = null;
                try {
                    URL url = new URL(uri);
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    StringBuilder sb = new StringBuilder();

                    bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));

                    String json;
                    while((json = bufferedReader.readLine())!= null){
                        sb.append(json+"\n");
                    }

                    return sb.toString().trim();

                }catch(Exception e){
                    return null;
                }

            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                loading.dismiss();
                textViewJSON.setText(s);
            }
        }
        GetJSON gj = new GetJSON();
        gj.execute(url);
    }
}

Android:-activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/etcheck"/>


    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/button_get"
        android:id="@+id/buttonGet" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:maxLines="20"
        android:scrollbars="vertical"
        android:id="@+id/textViewJSON" />
   <!-- <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/txtCheck"/> -->
<!--
    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Parse JSON"
        android:id="@+id/buttonParse" /> -->


</LinearLayout>

PHP file-

<?php
$con=mysqli_connect("localhost","amodbina0106","Amodbina200","kezin_king");
if ($con->connect_error) {
    die("Connection failed: " . $con->connect_error);
} 

?>

<?php
$sql=mysqli_query($con,"SELECT * FROM `Test` WHERE 1");
$result=array();
while($row=mysqli_fetch_assoc($sql))
{
    $result[]=$row;
}
echo json_encode(array("result"=>$result));
?>

Output of php:-

{"result":[{"Vendor_ID":"1","username":"nupur","password":"nupur"},{"Vendor_ID":"4","username":"","password":""},{"Vendor_ID":"3","username":"nupur","password":"1234"},{"Vendor_ID":"5","username":"RAJ","password":"RAJ"},{"Vendor_ID":"6","username":"RAJ","password":"RAJ"},{"Vendor_ID":"7","username":"","password":""},{"Vendor_ID":"8","username":"","password":""},{"Vendor_ID":"9","username":"","password":""},{"Vendor_ID":"10","username":"","password":""},{"Vendor_ID":"11","username":"","password":""},{"Vendor_ID":"12","username":"RAM","password":"RAM"},{"Vendor_ID":"13","username":"RAM","password":"RAM"},{"Vendor_ID":"14","username":"RAM","password":"RAM"},{"Vendor_ID":"15","username":"RAM","password":"RAM"},{"Vendor_ID":"16","username":"Nupur","password":"Nupur"},{"Vendor_ID":"17","username":"Nupur","password":"Nupur"},{"Vendor_ID":"18","username":"Nupur","password":"Nupur"},{"Vendor_ID":"19","username":"Nupur","password":"Nupur"},{"Vendor_ID":"20","username":"Rohit","password":"Rohit"},{"Vendor_ID":"21","username":"RAM","password":"RAM"},{"Vendor_ID":"22","username":"","password":""},{"Vendor_ID":"23","username":"","password":""},{"Vendor_ID":"24","username":"RAM","password":"RAM"},{"Vendor_ID":"35","username":"SAGAR","password":"SAGAR"},{"Vendor_ID":"34","username":"SAGAR","password":"SAGAR"},{"Vendor_ID":"33","username":"SAGAR","password":"SAGAR"},{"Vendor_ID":"32","username":"RAM","password":"RAM"},{"Vendor_ID":"31","username":"","password":""},{"Vendor_ID":"36","username":"SAGAR","password":"SAGAR"},{"Vendor_ID":"37","username":"SAGAR","password":"SAGAR"},{"Vendor_ID":"38","username":"SAGAR","password":"SAGAR"},{"Vendor_ID":"39","username":"SAGAR","password":"SAGAR"},{"Vendor_ID":"40","username":"SAGAR","password":"SAGAR"},{"Vendor_ID":"41","username":"SAGAR","password":"SAGAR"},{"Vendor_ID":"73","username":"","password":""},{"Vendor_ID":"43","username":"SAGAR","password":"SAGAR"},{"Vendor_ID":"44","username":"SAGAR","password":"SAGAR"},{"Vendor_ID":"45","username":"SAGAR","password":"SAGAR"},{"Vendor_ID":"46","username":"SAGAR","password":"SAGAR"},{"Vendor_ID":"47","username":"username","password":"password"},{"Vendor_ID":"74","username":"SAGAR","password":"SAGAR"},{"Vendor_ID":"75","username":"SAGAR","password":"SAGAR"},{"Vendor_ID":"72","username":"Krishna","password":"Krishna"},{"Vendor_ID":"68","username":"Honey","password":"Honey"},{"Vendor_ID":"69","username":"Ram","password":"Ram"},{"Vendor_ID":"70","username":"Ram","password":"Ram"},{"Vendor_ID":"71","username":"Ram","password":"Ram"}]}

Example:-If I provide the Vendor_ID in edittext as 1 It should provide me the username:- nupur password:- nupur in the text view.

3 Answers3

0

Use the JSONObject class it'll make like easier.

First retrieve what's in the editText with:

String token = editText.getText().toSting().trim();// token = Vendor_ID

then with the response you got from the web server which I'll call JSONString create a new JSONObject

JSONObject jo = new JSONObject(JSONString);

with the JSONObject you can retrieve any value. Look through the docs to see how to retrieve different kinds of data, but for now I'm assuming the data you're retrieving is a String.

String userName = JSONObject.getString(token);

with this userName shoulb be "nupur"

P.S it's bad practice to store passwords in plain text

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Olumide
  • 758
  • 13
  • 31
0

The easy way, you can use JSON parser like Gson. If you want to use the built-in library from android(org.json), you can use something like this

String jsonString = "{\"result\":[{\"Vendor_ID\":\"1\",\"username\":\"nupur\",\"password\":\"nupur\"},{\"Vendor_ID\":\"4\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"3\",\"username\":\"nupur\",\"password\":\"1234\"},{\"Vendor_ID\":\"5\",\"username\":\"RAJ\",\"password\":\"RAJ\"},{\"Vendor_ID\":\"6\",\"username\":\"RAJ\",\"password\":\"RAJ\"},{\"Vendor_ID\":\"7\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"8\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"9\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"10\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"11\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"12\",\"username\":\"RAM\",\"password\":\"RAM\"},{\"Vendor_ID\":\"13\",\"username\":\"RAM\",\"password\":\"RAM\"},{\"Vendor_ID\":\"14\",\"username\":\"RAM\",\"password\":\"RAM\"},{\"Vendor_ID\":\"15\",\"username\":\"RAM\",\"password\":\"RAM\"},{\"Vendor_ID\":\"16\",\"username\":\"Nupur\",\"password\":\"Nupur\"},{\"Vendor_ID\":\"17\",\"username\":\"Nupur\",\"password\":\"Nupur\"},{\"Vendor_ID\":\"18\",\"username\":\"Nupur\",\"password\":\"Nupur\"},{\"Vendor_ID\":\"19\",\"username\":\"Nupur\",\"password\":\"Nupur\"},{\"Vendor_ID\":\"20\",\"username\":\"Rohit\",\"password\":\"Rohit\"},{\"Vendor_ID\":\"21\",\"username\":\"RAM\",\"password\":\"RAM\"},{\"Vendor_ID\":\"22\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"23\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"24\",\"username\":\"RAM\",\"password\":\"RAM\"},{\"Vendor_ID\":\"35\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"34\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"33\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"32\",\"username\":\"RAM\",\"password\":\"RAM\"},{\"Vendor_ID\":\"31\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"36\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"37\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"38\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"39\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"40\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"41\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"73\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"43\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"44\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"45\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"46\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"47\",\"username\":\"username\",\"password\":\"password\"},{\"Vendor_ID\":\"74\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"75\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"72\",\"username\":\"Krishna\",\"password\":\"Krishna\"},{\"Vendor_ID\":\"68\",\"username\":\"Honey\",\"password\":\"Honey\"},{\"Vendor_ID\":\"69\",\"username\":\"Ram\",\"password\":\"Ram\"},{\"Vendor_ID\":\"70\",\"username\":\"Ram\",\"password\":\"Ram\"},{\"Vendor_ID\":\"71\",\"username\":\"Ram\",\"password\":\"Ram\"}]}";
int idYouWantToSearch = Integer.parseInt(editTextThatHasIdYouWantToSearch.getText().toString());
String username = "";
String password = "";
try {
    JSONObject jsonObject = new JSONObject(jsonString);
    JSONArray result = jsonObject.getJSONArray("result");
    //iterate through json array and check if id is same with your search
    for (int i = 0; i < result.length(); i++) {
        JSONObject item = result.getJSONObject(i);
        int id = item.getInt("Vendor_ID");
        if (id == idYouWantToSearch) {
            username = item.getString("username");
            password = item.getString("password");
            break;
        }
    }
} catch (JSONException e) {
    e.printStackTrace();
}
//here you can show the result
Log.v(this.getClass().getSimpleName(), "username = " + username);
Log.v(this.getClass().getSimpleName(), "password = " + password);
HendraWD
  • 2,984
  • 2
  • 31
  • 45
0

Considering we're talking client side here (Android) I would recommend Using Retrofit2 or Volley, these libraries allow you to manage your networking better, both handle the background threads for you (and are known to be better than AsyncTask, you can google it), and regarding JSON parsing - it would be good to use a library as well, like GSON, or maybe other stuff out there.

so what you have is this:

  1. Get a library for Networking.
  2. Get a library for JSON parsing.
  3. Integrate both together (create wrappers, interfaces, callbacks, etc.)

Retrofit has an option to add converters directly so it'll save you a nice part of the parsing yourself (unless you need more flexibility in the parsing process in which case you can look for more help here on Stack Overflow.

Now, about the parsing - the correct way to go about it would be-

  1. Parse the JSON object you receive.
  2. Use that to send another request to your server.

e.g - request with username is received by client -> parsed -> user completes password -> info is sent back again

Some stuff that might be useful:

Volley Example

Retrofit Example for custom requests

Hope this helps, and anyway- read more about the subject of REST API consuming.

Community
  • 1
  • 1
TommySM
  • 3,793
  • 3
  • 24
  • 36