#android #navigation-drawer
#Android #навигация-ящик
Вопрос:
Я использую действие ящика навигации. Я хочу отобразить настроенный список после получения данных из URL. Вот моя активность в ящике навигации.
Например: когда пользователь нажимает вкладку выделения в навигационном ящике, появляется действие выделения с настраиваемым представлением списка, отображающим данные URL.
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_dashboard) {
switch (item.getItemId()) {case R.id.nav_dashboard:
startActivity(new Intent(this, AdminDashBoardActivity.class));
// Handle the camera action
} }
else if (id == R.id.nav_allocations) {
switch (item.getItemId()) {case R.id.nav_allocations:
startActivity(new Intent(this,
AdminAllocationActivity.class));
break;
// Handle the camera action
}
} else if (id == R.id.nav_courseoutline) {
switch (item.getItemId()) {
case R.id.nav_courseoutline:
startActivity(new Intent(this, CourseOutlineActivity.class)); }
} else if (id == R.id.nav_ranklist) {
switch (item.getItemId()) {case R.id.nav_ranklist:
startActivity(new Intent(this,AllocatedTrainerActivity .class));
}}
// else if (id == R.id.nav_send) {
//
// }
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
когда пользователь нажимает на вкладку распределения, открывается действие по распределению и отображается результат проанализированных данных в настраиваемом списке, но этого не происходит. пожалуйста, направьте меня.Вот моя деятельность по распределению.
package vu.bc110201891.btg.AdminActivities;
import android.content.Intent;
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;
import vu.bc110201891.btg.Adapters.AdminAllocationAdapter;
import vu.bc110201891.btg.AsyncTasks.AdminAllocationTask;
import vu.bc110201891.btg.Models.AdminAllocation;
import vu.bc110201891.btg.R;
public class AdminAllocationActivity extends AppCompatActivity {
String json_string;
JSONObject jsonObject;
JSONArray jsonArray;
ListView listView;
AdminAllocationAdapter contactAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_allocation);
listView= (ListView) findViewById(R.id.listView);
contactAdapter=new AdminAllocationAdapter(this,R.layout.activity_admin_allocation);
listView.setAdapter(contactAdapter);
json_string=getIntent().getExtras().getString("json_data");
try {
jsonObject=new JSONObject(json_string);
jsonArray=jsonObject.getJSONArray("courseDataSet");
int count=0;
String name,email,moblile;
while (count<jsonArray.length()){
JSONObject JO=jsonArray.getJSONObject(count);
name=JO.getString("id");
email= JO.getString("company_id");
moblile=JO.getString("user_id");
AdminAllocation contacts=new AdminAllocation(name,email,moblile);
contactAdapter.add(contacts);
count ;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
вот мой adpater.
package vu.bc110201891.btg.Adapters;
import android.content.Context;
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;
import vu.bc110201891.btg.Models.AdminAllocation;
import vu.bc110201891.btg.R;
/**
* Created by bc120402700 on 9/23/2016.
*/
public class AdminAllocationAdapter extends ArrayAdapter {
List list=new ArrayList();
public AdminAllocationAdapter(Context context, int resource) {
super(context, resource);
}
public void add(AdminAllocation object) {
super.add(object);
list.add(object);
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
row=convertView;
AllocationHolder contactHolder;
if (row==null){
LayoutInflater layoutInflater= (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row=layoutInflater.inflate(R.layout.row_allocation,parent,false);
contactHolder=new AllocationHolder();
contactHolder.tx_name= (TextView) row.findViewById(R.id.textView2);
contactHolder.tx_email= (TextView) row.findViewById(R.id.textView3);
// contactHolder.tx_mobile= (TextView) row.findViewById(R.id.tx_mobile);
row.setTag(contactHolder);
}
else {
contactHolder=(AllocationHolder)row.getTag();
}
AdminAllocation contacts= (AdminAllocation) this.getItem(position);
contactHolder.tx_name.setText(contacts.getName());
contactHolder.tx_email.setText(contacts.getEmail());
contactHolder.tx_mobile.setText(contacts.getMobile());
return row;
}
static class AllocationHolder{
TextView tx_name,tx_email,tx_mobile;
}
}
вот моя задача asyn.
package vu.bc110201891.btg.AsyncTasks;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Button;
import android.widget.TextView;
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;
import vu.bc110201891.btg.R;
/**
* Created by bc120402700 on 9/23/2016.
*/
public class AdminAllocationTask extends AsyncTask<Void, Void, String> {
String json_url;
@Override
protected void onPreExecute() {
json_url = "http://mantis.vu.edu.pk/bridging_the_gap/public/AllocateAdminService";
}
String JSON_STRING;
@Override
protected String doInBackground(Void... voids) {
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) {
super.onPostExecute(result);}
}
это мой класс модели.
package vu.bc110201891.btg.Models;
public class AdminAllocation {
private String name,email,mobile;
public AdminAllocation(String name, String email, String mobile){
this.name=name;
this.email=email;
this.mobile=mobile;
} public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMobile() {
return mobile;
}public void setMobile(String mobile) {
this.mobile = mobile;
}public String getEmail() {
return email; }
public void setEmail(String email) {
this.email = email;
}
}
Ответ №1:
Установите адаптер в listview после получения значений
listView.setAdapter(contactAdapter);
добавьте эту строку после этого кодирования
json_string=getIntent().getExtras().getString("json_data");
try {
jsonObject=new JSONObject(json_string);
jsonArray=jsonObject.getJSONArray("courseDataSet");
int count=0;
String name,email,moblile;
while (count<jsonArray.length()){
JSONObject JO=jsonArray.getJSONObject(count);
name=JO.getString("id");
email= JO.getString("company_id");
moblile=JO.getString("user_id");
AdminAllocation contacts=new AdminAllocation(name,email,moblile);
contactAdapter.add(contacts);
count ;
}
} catch (JSONException e) {
e.printStackTrace();
}
Правильный код
json_string=getIntent().getExtras().getString("json_data");
try {
jsonObject=new JSONObject(json_string);
jsonArray=jsonObject.getJSONArray("courseDataSet");
int count=0;
String name,email,moblile;
while (count<jsonArray.length()){
JSONObject JO=jsonArray.getJSONObject(count);
name=JO.getString("id");
email= JO.getString("company_id");
moblile=JO.getString("user_id");
AdminAllocation contacts=new AdminAllocation(name,email,moblile);
contactAdapter.add(contacts);
count ;
}
} catch (JSONException e) {
e.printStackTrace();
}
listView.setAdapter(contactAdapter);
Комментарии:
1. все еще выдает ошибку и не показывает результат. это моя ошибка.
2. Попытка вызвать виртуальный метод ‘java.lang. Строка android.os.Bundle.getString(java.lang. Строка)’ на нулевой ссылке на объект в vu.bc110201891.btg.AdminActivities. AdminAllocationActivity.onCreate(AdminAllocationActivity.java:33)
3. Может быть любое целое или двойное значение, которое следует читать как строку. Пожалуйста, проверьте это