如何在setonItemClickListener中从现有listview创建新的json listview

时间:2016-10-18 13:45:01

标签: java android json listview android-studio

所以我设法在点击按钮时显示我的类别列表,它会启动新活动并显示我的列表。问题在于我实施onItemClick listener和Toast一些有效或开始新活动的数据并在TextView中显示一些ID - > 当我创建一个新的ListView,甚至做同样的应用程序崩溃...有几个json文件,它们是结构化的:url:http / ...... com / id所以这个id提供了下一个url json文件的id - >当前类别的子类别我做错了什么?

MainActivity - 获取json文件

public class MainActivity extends AppCompatActivity {

String json_string;
String urlEnd;
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ActionBar actionBar = getSupportActionBar();
    actionBar.setDisplayShowHomeEnabled(true);
    actionBar.setIcon(R.mipmap.full_logo);

    TextView t2 = (TextView) findViewById(R.id.forgot_password_link);
    t2.setMovementMethod(LinkMovementMethod.getInstance());
    getJson("1");
}
public String setUrl(String importantNumber){
    String json_url;
    json_url = "http://...." + importantNumber;
    return json_url;
}

public void getJson(String idkategorije){
    new BackgroundTask(idkategorije).execute();
}

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

    private final String idkategorije;
    String json_url;
    String line;

    public BackgroundTask(String idkategorije) {
        this.idkategorije = idkategorije;
    }

    @Override
    protected void onPreExecute() {
        json_url = setUrl(idkategorije);
    }

    @Override
    protected String doInBackground(Void... voids) {
        try{
            URL url = new URL(json_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.connect();

            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

            StringBuilder stringBuilder = new StringBuilder();
            while ((line = bufferedReader.readLine()) != null){
                stringBuilder.append(line);
            }
            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) {
        json_string = result;
    }
}

public void parseJSON(View view){
    if (json_string == null){
        Toast.makeText(getApplicationContext(), "GetJson", Toast.LENGTH_SHORT).show();
    }else{
        Intent intent = new Intent(this, DisplayListView.class);
        intent.putExtra("json_data", json_string);
        startActivity(intent);
    }
}

public void forgotPassword(View view) {
    //specify an intent --> directs to new activity --> ForgotPassword.class
    Intent startForgotPassActivity = new Intent(this, ForgotPassword.class);
    startActivity(startForgotPassActivity);
}

public void registration(View view) {
    Intent registrationActivity = new Intent(this, registration.class);
    startActivity(registrationActivity);
}

public void addfile(View view) {
    Intent addfileActivity = new Intent(this, Addfile.class);
    startActivity(addfileActivity);
}
public void login(View view) {
    Intent loginActivity = new Intent(this, login.class);
    startActivity(loginActivity);
}

public void Searchme(View view) {
    EditText searchInput = (EditText)findViewById(R.id.id_search_input);
    String searchString = searchInput.getText().toString(); //URL nastavak

    Intent searchActivity = new Intent(this, search.class);
    searchActivity.putExtra("url",searchString);
    startActivity(searchActivity);
}
}

正在使用DisplayListView.java

public class DisplayListView extends AppCompatActivity {

String json_string;
JSONArray jsonArray;
CategoryAdapter categoryAdapter;
ListView listView;
String prosljedeni;

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

    ActionBar actionBar = getSupportActionBar();
    actionBar.setDisplayShowHomeEnabled(true);
    actionBar.setIcon(R.mipmap.full_logo);

    listView = (ListView) findViewById(R.id.listview);
    categoryAdapter = new CategoryAdapter(this, R.layout.row_layout);
    listView.setAdapter(categoryAdapter);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id){

            Categories categories = (Categories) categoryAdapter.getItem(position);
            String idkat = categories.getId(); //dohvati id imena reda

            Toast.makeText(getApplicationContext(), idkat, Toast.LENGTH_SHORT).show();
            //MainActivity mm = new MainActivity();
            //mm.new BackgroundTask(idkat).execute();

            Intent intent = new Intent(DisplayListView.this, SubCategory.class);
            intent.putExtra("idkat",idkat);
            startActivity(intent);
        }
    });

    json_string = getIntent().getExtras().getString("json_data");
    //inicjalizacija jsonObject
    try {
        //jsonObject = new JSONObject(json_string); //starts with [ not {
        jsonArray = new JSONArray(json_string); //get the array
        int count = 0;
        String name;
        String urlFromJ;
        String parentId;
        String idKategorije;

        while (count < jsonArray.length()) {
            JSONObject JO = jsonArray.getJSONObject(count);

            idKategorije = JO.getString("id");
            parentId = JO.getString("parent_id");
            name = JO.getString("name");
            urlFromJ = JO.getString("url");

            Categories categories = new Categories(idKategorije, parentId, name, urlFromJ);
            categoryAdapter.add(categories);
            count++;
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}
}

我的适配器......类别适配器

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

public void add(Categories 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, View convertView, ViewGroup parent) {
    View row;
    row = convertView;
    CategoryHolder categoryHolder;
    if (row == null){
        LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        row = layoutInflater.inflate(R.layout.row_layout, parent, false);
        categoryHolder = new CategoryHolder();
        categoryHolder.tx_name = (TextView) row.findViewById(R.id.tx_name);
        row.setTag(categoryHolder);

    }else {
        categoryHolder = (CategoryHolder) row.getTag();
    }
    //set resources for Views
    Categories categories = (Categories) this.getItem(position);
    //set resource for category holder

    categoryHolder.tx_name.setText(categories.getName());
    //categoryHolder.tx_name.setText(categories.getUrlFromJson());
    return row;
}

static class CategoryHolder{
    TextView tx_name;
}
}

Categories.java - getter and setters

public class Categories {
private String name;
private String urlFromJson;
private String parentId;
private String id;

public Categories(String id, String parentId, String name, String urlFromJson) {
    this.id = id;
    this.parentId = parentId;
    this.name = name;
    this.urlFromJson = urlFromJson;
}

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getUrlFromJson() {
    return urlFromJson;
}

public void setUrlFromJson(String urlFromJson) {
    this.urlFromJson = urlFromJson;
}

public String getParentId() {
    return parentId;
}

public void setParentId(String parentId) {
    this.parentId = parentId;
}
}

记录错误

FATAL EXCEPTION: main
Process: hr.oglasnik.perhpethua.oo, PID: 24222
java.lang.RuntimeException: Unable to start activity ComponentInfo{hr.oglasnik.perhpethua.oo/hr.oglasnik.perhpethua.oo.SubCategory}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2439)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2495)
at android.app.ActivityThread.access$800(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5633)
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:896)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:712)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
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 hr.oglasnik.perhpethua.oo.SubCategory.onCreate(SubCategory.java:69)
at android.app.Activity.performCreate(Activity.java:5312)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1111)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2395)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2495) 
at android.app.ActivityThread.access$800(ActivityThread.java:153) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:157) 
at android.app.ActivityThread.main(ActivityThread.java:5633) 
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:896) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:712) 
at dalvik.system.NativeStart.main(Native Method) 

0 个答案:

没有答案