0

I'm doing a Final Project for my class and everything is going smoothly and then i try to run the app, crashes on my phone and this:

04-29 13:36:24.185 3507-3507/com.example.jessewmoore.database2 E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.jessewmoore.database2, PID: 3507 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.jessewmoore.database2/com.example.jessewmoore.database2.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3184) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3294) at android.app.ActivityThread.access$1000(ActivityThread.java:210) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1704) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:145) at android.app.ActivityThread.main(ActivityThread.java:6938) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116) at org.json.JSONTokener.nextValue(JSONTokener.java:94) at org.json.JSONArray.(JSONArray.java:92) at org.json.JSONArray.(JSONArray.java:108) at com.example.jessewmoore.database2.MainActivity.onCreate(MainActivity.java:72) at android.app.Activity.performCreate(Activity.java:6575) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1134) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3137) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3294)  at android.app.ActivityThread.access$1000(ActivityThread.java:210)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1704)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:145)  at android.app.ActivityThread.main(ActivityThread.java:6938)  at java.lang.reflect.Method.invoke(Native Method)  at java.lang.reflect.Method.invoke(Method.java:372)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199) 

every thing shoul dbe good there are no errors.

activity_main

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<HorizontalScrollView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:focusableInTouchMode="true"
    android:focusable="true">

    <TableLayout android:id="@+id/table"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:focusableInTouchMode="true"
        android:focusable="true"></TableLayout>

 </HorizontalScrollView>
 </ScrollView>

AndroidManifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.jessewmoore.database2">
<uses-permission android:name="android.permission.INTERNET"/>
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

</manifest>

MainActivity

package com.example.jessewmoore.database2;

 import java.io.BufferedReader;
 import java.io.InputStream;
 import java.io.InputStreamReader;
 import org.apache.http.HttpEntity;
 import org.apache.http.HttpResponse;
 import org.apache.http.client.HttpClient;
 import org.apache.http.client.methods.HttpPost;
 import org.apache.http.impl.client.DefaultHttpClient;
 import org.json.JSONArray;
 import org.json.JSONException;
 import org.json.JSONObject;
 import android.app.Activity;
 import android.graphics.Color;
 import android.os.Bundle;
 import android.util.Log;
 import android.view.View;
 import android.widget.Button;
 import android.widget.TableLayout;
 import android.widget.TableRow;
 import android.widget.TextView;
 import android.widget.Toast;
 import android.widget.TableRow.LayoutParams;

 public class MainActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    String result = null;
    InputStream is = null;
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http: busdata.pe.hu/myfile.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 results" + 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(MainActivity.this);
            tr.setLayoutParams(new LayoutParams(
                    LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT));
            if (flag == 1) {
                TextView b6 = new TextView(MainActivity.this);
                b6.setText("Id");
                b6.setTextColor(Color.BLUE);
                b6.setTextSize(15);
                tr.addView(b6);
                TextView b19 = new TextView(MainActivity.this);
                b19.setPadding(10, 0, 0, 0);
                b19.setTextSize(15);
                b19.setText("Name");
                b19.setTextColor(Color.BLUE);
                tr.addView(b19);
                TextView b29 = new TextView(MainActivity.this);
                b29.setPadding(10, 0, 0, 0);
                b29.setText("Status");
                b29.setTextColor(Color.BLUE);
                b29.setTextSize(15);
                tr.addView(b29);
                tv.addView(tr);
                final View vline = new View(MainActivity.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", "id: " + json_data.getInt("Id") + ", Username: " + json_data.getString("username") + ", No:" + json_data.getString("comment"));
                TextView b = new TextView(MainActivity.this);
                String stime = String.valueOf(json_data.getInt("Id"));
                b.setText(stime);
                b.setTextColor(Color.RED);
                b.setTextSize(15);
                tr.addView(b);
                TextView b1 = new TextView(MainActivity.this);
                b1.setPadding(10, 0, 0, 0);
                b1.setTextSize(15);
                String stime1 = json_data.getString("username");
                b1.setText(stime1);
                b1.setTextColor(Color.BLACK);
                tr.addView(b1);
                TextView b2 = new TextView(MainActivity.this);
                b2.setPadding(10, 0, 0, 0);
                String stime2 = json_data.getString("comment");
                b2.setText(stime2);
                b2.setTextColor(Color.BLACK);
                b2.setTextSize(15);
                tr.addView(b2);
                tv.addView(tr);
                final View vline1 = new View(MainActivity.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();
    }

    }

   }
Yaseen Ahmad
  • 1,807
  • 5
  • 25
  • 43

1 Answers1

0

Your error is a NullPointerException, caused by line 72 in MainActivity.java which is:

JSONArray jArray = new JSONArray(result);

To read further into your error, it seems JSONArray attempted to invoke length() on result, likely while it was attempting to construct the appropriate JSON array from the string. Being able to understand these errors is important to solving your problem, and helps you ask better questions!

You initially set result to null - it seems it is not getting set properly before calling new JSONArray(result). A good place to start is check that the try block directly before it that initializes result completes correctly and does not fail. Perhaps you have something in your log prior to the error from the catch statement on your 'convert response to string' try block.

HunterCM
  • 121
  • 5
  • result is set to this right before the array String result = null; – jesse moore Apr 29 '16 at 19:10
  • That is inside a try catch block, though. The try block could encounter an exception and then result would never be set. Instead, you would output "Error converting results" to your log. Try debugging with a breakpoint as AgileNinja suggested and you should find result is null at line 72. *edit since you changed your comment to show result = null: That is exactly my point... – HunterCM Apr 29 '16 at 19:14