0

i want help in creating a php file for database to attach it to my server and use it for json parsing.also i dont know how to create a specific json relating to a php file. i just want to create an app to fetch text data from server. ** Any info on how to create a php n its json will be very helpful.**

This is my MainActivity.java class

public class MainActivity extends ActionBarActivity implements View.OnClickListener {

private TextView textViewJSON;
private Button buttonGet;
private Button buttonParse;

public static final String MY_JSON ="MY_JSON";

private static final String JSON_URL = "\n" +
        "http://file-manager.000webhost.com/file-manager/index.php";

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

    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 void onClick(View v) {
    if(v==buttonGet){
        getJSON(JSON_URL);
    }

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

private void showParseActivity() {
    Intent intent = new Intent(this, ParseJSON.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);
}
}

This is my ParserJson.java class

public class ParseJSON extends ActionBarActivity implements   View.OnClickListener{

private String myJSONString;

private static final String JSON_ARRAY ="result";
private static final String ID = "id";
private static final String USERNAME= "name";

private JSONArray users = null;

private int TRACK = 0;

private EditText editTextId;
private EditText editTextUserName;
private EditText editTextPassword;

Button btnPrev;
Button btnNext;

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

    Intent intent = getIntent();
    myJSONString = intent.getStringExtra(MainActivity.MY_JSON);


    editTextId = (EditText) findViewById(R.id.editTextID);
    editTextUserName = (EditText) findViewById(R.id.editTextUsername);
    editTextPassword = (EditText) findViewById(R.id.editTextPassword);

    btnPrev = (Button) findViewById(R.id.buttonPrev);
    btnNext = (Button) findViewById(R.id.buttonNext);

    btnPrev.setOnClickListener(this);
    btnNext.setOnClickListener(this);

    extractJSON();

    showData();
}



private void extractJSON(){
    try {
        JSONObject jsonObject = new JSONObject(myJSONString);
        //users =new JSONArray(JSON_ARRAY);
        users = jsonObject.getJSONArray(JSON_ARRAY);
      //  JSONObject jsonObject =users.getJSONObject(0);
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

private void moveNext(){
    if(TRACK<users.length()){
        TRACK++;
    }
    showData();
}

private void movePrev(){
    if(TRACK>0){
        TRACK--;
    }
    showData();
}

private void showData(){
    try {
        JSONObject jsonObject = users.getJSONObject(TRACK);

        editTextId.setText(jsonObject.getString(ID));
        editTextUserName.setText(jsonObject.getString(USERNAME));

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

}


@Override
public void onClick(View v) {
    if(v == btnNext){
        moveNext();
    }
    if(v == btnPrev){
        movePrev();
    }
}
}

This is my php file stored in public html folder of file manager.i also dont know where to store this file which tells about my database. The name of my php file is mark42.php but it is saving as index.php.

<?php
define('HOST','mysql9.000webhost.com');
define('USER','**********');
define('PASS','******');
define('DB','a4023522_db');$con = mysqli_connect(HOST,USER,PASS,DB);    $sql = "select * from mark42";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,array('id'=>$row[0],'name'=>$row[1]));
}
echo json_encode(array("result"=>$result));
mysqli_close($con);
?>

This is my logcat error, app crashes when I press the parsejson button.

    FATAL EXCEPTION: main Process: test.nic.com.nicpro, PID: 6506
java.lang.RuntimeException: Unable to start activity ComponentInfo{test.nic.com.nicpro/test.nic.com.nicpro.ParseJSON}: java.lang.NullPointerException: Attempt to invoke virtual method 'org.json.JSONObject org.json.JSONArray.getJSONObject(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'org.json.JSONObject org.json.JSONArray.getJSONObject(int)' on a null object reference
at test.nic.com.nicpro.ParseJSON.showData(ParseJSON.java:94)
at test.nic.com.nicpro.ParseJSON.onCreate(ParseJSON.java:62)
at android.app.Activity.performCreate(Activity.java:6251)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
Abhishek Rai
  • 19
  • 1
  • 1
  • 8

2 Answers2

1
JSONObject jsonObject = users.getJSONObject(TRACK)

is throwing a NullPointerException. That means that your line:

users = jsonObject.getJSONArray(JSON_ARRAY);

is setting users to null. Double check that the array actually exists in your object, and that you haven't accidentally used the wrong key

Jeeter
  • 5,887
  • 6
  • 44
  • 67
  • thanks i will see into this. – Abhishek Rai Jul 30 '16 at 06:32
  • i found the answer to the problem simply by changing ActionBarActivity to AppCompatActivity.the null pointer exception vanished automatically! @http://stackoverflow.com/users/116938/austyn-mahoney can you explain this why this happened! – Abhishek Rai Jul 30 '16 at 15:43
0

You need to learn how to use the debugger.

Put a breakpoint on:

JSONObject jsonObject = new JSONObject(myJSONString);

Then run your program in debug mode.

When it stops on that line, hover your mouse on myJSONString and see what the value is. It's a safe bet it's not what you're expecting.