Ошибка приложения при анализе json

106
10

В моем MainActivity.java

    package rjj.tutorial_jsonandlistview;

import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Text;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

String Json_STRING;

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

public void getJSON(View view) {

new BackgroundTask().execute();

}

class BackgroundTask extends AsyncTask<Void, Void, String>{

String json_url;
String JSON_STRING;
@Override
protected void onPreExecute() {
json_url = "http://kreen155.000webhostapp.com/rizal.php";
}

@Override
protected String doInBackground(Void... params) {
try {
URL url = new URL(json_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
while ((JSON_STRING = bufferedReader.readLine()) != null) {

stringBuilder.append(JSON_STRING+"\n");
}

bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

return null;
}

@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}

@Override
protected void onPostExecute(String result) {
TextView textView = (TextView)findViewById(R.id.textView2);
textView.setText(result);
Json_STRING = result;
}
}
//List view time!
public void parseJSON(View view) {

if(Json_STRING == null){
Toast.makeText(getApplicationContext(), "First Get JSON", Toast.LENGTH_SHORT).show();
}else{
Intent intent = new Intent(this, DisplayListView.class);
intent.putExtra("json_data", Json_STRING);
startActivity(intent);
}

}

}

Мой пакет DisplayListView.java rjj.tutorial_jsonandlistview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class DisplayListView extends AppCompatActivity {

String json_string;
JSONObject jsonObject;
JSONArray jsonArray;
ContactAdapter contactAdapter;
ListView listView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_listview_layout);
listView = (ListView)findViewById(R.id.listview);

contactAdapter = new ContactAdapter(this,R.layout.row_layout);
listView.setAdapter(contactAdapter);
json_string = getIntent().getExtras().getString("json_data");

try {
jsonObject = new JSONObject(json_string);
jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
String id ,firstname , surname, age , username, password;

while(count<jsonObject.length()){
JSONObject JO = jsonArray.getJSONObject(count);
id = JO.getString("id");
firstname = JO.getString("firstname");
surname = JO.getString("surname");
age = JO.getString("age");
username = JO.getString("username");
password = JO.getString("password");
Contacts contact = new Contacts(id, firstname, surname, age,username,password);
contactAdapter.add(contact);

count++;

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

}
}

В моем ContactAdapter.java

package rjj.tutorial_jsonandlistview;

import android.content.Context;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

/**
* Created by Julian on 7/20/2017.
*/

public class ContactAdapter extends ArrayAdapter {
List list = new ArrayList();
public ContactAdapter(@NonNull Context context, @LayoutRes int resource) {
super(context, resource);
}

public void add(Contacts object) {
super.add(object);
list.add(object);
}

@Override
public int getCount() {
return list.size();
}

@Nullable
@Override
public Object getItem(int position) {
return list.get(position);
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {

View row;
row = convertView;
ContactHolder contactHolder;
if(row == null){
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.row_layout,parent,false);
contactHolder = new ContactHolder();
contactHolder.tx_id = (TextView)row.findViewById(R.id.tx_id);
contactHolder.tx_firstname = (TextView)row.findViewById(R.id.tx_firstname);
contactHolder.tx_surname = (TextView)row.findViewById(R.id.tx_surname);
contactHolder.tx_username = (TextView)row.findViewById(R.id.tx_username);
contactHolder.tx_password = (TextView)row.findViewById(R.id.tx_password);
row.setTag(contactHolder);

} else{
contactHolder = (ContactHolder)row.getTag();
}
Contacts contacts = (Contacts)this.getItem(position);
contactHolder.tx_id.setText(contacts.getId());
contactHolder.tx_firstname.setText(contacts.getFirstname());
contactHolder.tx_surname.setText(contacts.getSurname());
contactHolder.tx_age.setText(contacts.getAge());
contactHolder.tx_username.setText(contacts.getUsername());
contactHolder.tx_password.setText(contacts.getPassword());
return row;
}

static class ContactHolder{
TextView tx_id, tx_firstname, tx_surname, tx_age, tx_username, tx_password;
}
}

В моем AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="rjj.tutorial_jsonandlistview">

<uses-permission android:name="android.permission.INTERNET" />

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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

</manifest>

В моей конструкции градиента

apply plugin: 'com.android.application'

android {
compileSdkVersion 25
buildToolsVersion "26.0.0"
defaultConfig {
applicationId "rjj.tutorial_jsonandlistview"
minSdkVersion 19
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
}

Другая конструкция градиента

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.3'

// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}

allprojects {
repositories {
jcenter()
}
}

task clean(type: Delete) {
delete rootProject.buildDir
}

Аварийный журнал впервые запускается/открывается:

07-20 23:34:40.668 6438-6438/rjj.tutorial_jsonandlistview E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering
07-20 23:34:41.398 6438-6438/rjj.tutorial_jsonandlistview E/EGL_emulation: tid 6438: eglSurfaceAttrib(1199): error 0x3009 (EGL_BAD_MATCH)

При нажатии на синтаксический разбор JSON:

07-20 23:34:40.668 6438-6438/rjj.tutorial_jsonandlistview E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering
07-20 23:34:41.398 6438-6438/rjj.tutorial_jsonandlistview E/EGL_emulation: tid 6438: eglSurfaceAttrib(1199): error 0x3009 (EGL_BAD_MATCH)
07-20 23:45:52.928 6438-6438/rjj.tutorial_jsonandlistview E/AndroidRuntime: FATAL EXCEPTION: main
Process: rjj.tutorial_jsonandlistview, PID: 6438
java.lang.NullPointerException
at rjj.tutorial_jsonandlistview.ContactAdapter.getView(ContactAdapter.java:68)
at android.widget.AbsListView.obtainView(AbsListView.java:2263)
at android.widget.ListView.measureHeightOfChildren(ListView.java:1263)
at android.widget.ListView.onMeasure(ListView.java:1175)
at android.view.View.measure(View.java:16497)
at android.widget.RelativeLayout.measureChild(RelativeLayout.java:689)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:473)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.support.v7.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:393)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2291)
at android.view.View.measure(View.java:16497)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1916)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1113)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1295)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5670)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
at android.view.Choreographer.doCallbacks(Choreographer.java:574)
at android.view.Choreographer.doFrame(Choreographer.java:544)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)

Я не знаю, что делать сейчас, я пробовал 3 учебника и все напрасно. Пожалуйста, помогите, что проблема с моими кодами.

спросил(а) 2021-01-19T14:37:25+03:00 2 месяца, 3 недели назад
1
Решение
62

Ошибка исходит из этой строки кода:

contactHolder.tx_age.setText(contacts.getAge());

вы не добавили

contactHolder.tx_age = (TextView)row.findViewById(R.id.tx_age);

в этом коде:

if(row == null){
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.row_layout,parent,false);
contactHolder = new ContactHolder();
contactHolder.tx_id = (TextView)row.findViewById(R.id.tx_id);
contactHolder.tx_firstname = (TextView)row.findViewById(R.id.tx_firstname);
contactHolder.tx_surname = (TextView)row.findViewById(R.id.tx_surname);
contactHolder.tx_username = (TextView)row.findViewById(R.id.tx_username);
contactHolder.tx_password = (TextView)row.findViewById(R.id.tx_password);
row.setTag(contactHolder);

ответил(а) 2021-01-19T14:37:25+03:00 2 месяца, 3 недели назад
Ваш ответ
Введите минимум 50 символов
Чтобы , пожалуйста,
Выберите тему жалобы:

Другая проблема