Я очень новичок в android. Я знаю, что этот вопрос повторяется, я пробовал все решения из SO, но я облако не исправил свою проблему. Надеюсь, вы понимаете. Вот мой код для извлечения данных из MYSQL
и отображается в формате table
. Но я где-то застрял. Я пробовал много решений, чтобы исправить мою проблему, но я не смог получить результат. Каждый раз, когда я запускаю свое приложение, он продолжает раздаваться. Также мне не удалось отобразить данные в виде таблицы.'int java.lang.String.length()' на ссылке нулевого объекта
main.java
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://IP/stat_api/myjson.json");
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");
}
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(MainActivity.this);
tr.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
if (flag == 1) {
TextView tv1 = new TextView(MainActivity.this);
tv1.setText("eid");
tv1.setTextColor(Color.BLUE);
tv1.setTextSize(15);
tr.addView(tv1);
TextView tv2 = new TextView(MainActivity.this);
tv2.setPadding(10, 0, 0, 0);
tv2.setTextSize(15);
tv2.setText("name");
tv2.setTextColor(Color.BLUE);
tr.addView(tv2);
TextView tv3 = new TextView(MainActivity.this);
tv3.setPadding(10, 0, 0, 0);
tv3.setText("user_name");
tv3.setTextColor(Color.BLUE);
tv3.setTextSize(15);
tr.addView(tv3);
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", "eid: " + json_data.getInt("eid") + ", name: " + json_data.getString("name") + ", user_name: " + json_data.getString("user_name"));
TextView b = new TextView(MainActivity.this);
String stime = String.valueOf(json_data.getInt("eid"));
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("name");
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("user_name");
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();
}
}
}
myjson.json
[{
"eid": "1",
"name": "karthi",
"user_name": "admin",
"password": "rootsquare",
"privilege": "1",
"dob": "2016-09-03",
"address": "99, xyz bla bla, abc.",
"city": "cbe",
"mobile": "",
"blood_gp": "B+",
"status": "0"
}, {
"eid": "2",
"name": "raja",
"user_name": "emp",
"password": "emp",
"privilege": "2",
"dob": "2016-09-07",
"address": "100, abc, xyz, bla bla",
"city": "cbe",
"mobile": "9638527410",
"blood_gp": "A+",
"status": "0"
}, {
"eid": "3",
"name": "X",
"user_name": "xxx",
"password": "xxx",
"privilege": "2",
"dob": "2016-09-07",
"address": "cbe",
"city": "cbe",
"mobile": "",
"blood_gp": "A+",
"status": "0"
}, {
"eid": "4",
"name": "testuser",
"user_name": "testpwd",
"password": "255",
"privilege": "2",
"dob": "2016-09-01",
"address": "cbe",
"city": "cbe",
"mobile": "000000000",
"blood_gp": "A+",
"status": "0"
}, {
"eid": "5",
"name": "test",
"user_name": "userr",
"password": "testpwd",
"privilege": "2",
"dob": "1991-09-03",
"address": "cbe",
"city": "cbe",
"mobile": "000000000",
"blood_gp": "A+",
"status": "0"
}, {
"eid": "6",
"name": "karthi",
"user_name": "karthi",
"password": "karthi",
"privilege": "2",
"dob": "1991-09-03",
"address": "udt",
"city": "tip",
"mobile": "9500892145",
"blood_gp": "B+",
"status": "0"
}, {
"eid": "7",
"name": "raja",
"user_name": "raja",
"password": "raja",
"privilege": "2",
"dob": "1990-03-02",
"address": "cbe",
"city": "cbe",
"mobile": "",
"blood_gp": "A+",
"status": "0"
}, {
"eid": "8",
"name": "kk",
"user_name": "kk",
"password": "kk",
"privilege": "2",
"dob": "1991-02-03",
"address": "cbe",
"city": "cbe",
"mobile": "",
"blood_gp": "b+",
"status": "0"
}, {
"eid": "9",
"name": "zz",
"user_name": "zz",
"password": "zz",
"privilege": "2",
"dob": "2000-01-05",
"address": "cc",
"city": "cc",
"mobile": "9874254482",
"blood_gp": "o+",
"status": "0"
}]
Logcat:
Process: com.example.newtable.newtable, PID: 5668
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.newtable.newtable/com.example.newtable.newtable.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: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 '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.<init>(JSONArray.java:92)
at org.json.JSONArray.<init>(JSONArray.java:108)
at com.example.newtable.newtable.MainActivity.onCreate(MainActivity.java:65)
at android.app.Activity.performCreate(Activity.java:6237)
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)
, пожалуйста, разместите свой логарифм. –
yes bro i update it @SachinBahukhandi –
@ T.KarthikeyanT.Karthikeyan Вы действительно получаете результат в своем JSONArray или нет? Вы проверили это, отладив – GrIsHu