我不知道发生了什么,我无法运行我的应用。它的作用是从API获取一些信息数据并将其列在列表视图中,我认为我的ClienteActivity出了问题,但我不知道是什么。
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.android/com.android.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2198)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2257)
at android.app.ActivityThread.access$800(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5086)
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:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
**Caused by: java.lang.NullPointerException
at com.android.MainActivity.onCreate(MainActivity.java:40)**
at android.app.Activity.performCreate(Activity.java:5248)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2162)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2257)
at android.app.ActivityThread.access$800(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5086)
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:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
MainActivity:
public class MainActivity extends SherlockFragmentActivity {
private ViewPager mViewPager;
private TabsAdapter mTabsAdapter;
private ActionBar barra;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mViewPager = new ViewPager(this);
mViewPager.setId(R.id.pager);
setContentView(mViewPager);
mTabsAdapter = new TabsAdapter(this, mViewPager);
**mTabsAdapter.addTab(barra.newTab().setIcon(R.drawable.clientes).setText(" Clientes"), ClienteActivity.class, null);**
barra = getSupportActionBar();
barra.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
}
private static final int REFRESH = 1;
private static final int SEARCH = 2;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.main, menu);
menu.add(0, REFRESH, 0, "Refresh")
.setIcon(R.drawable.ic_action_view_as_grid)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
menu.add(0, SEARCH, 0, "Search")
.setIcon(R.drawable.ic_action_search)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case REFRESH:
return true;
case SEARCH:
// Do search
return true;
case R.id.add_item:
this.dispatchSync();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void dispatchSync() {
SincronizarTask mSincronizarTask = new SincronizarTask(this);
mSincronizarTask.inicia();
}
}
ClienteActivity:
public class ClienteActivity extends SherlockFragment {
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_cliente, container, false);
try {
ClienteViewAdapter ad = new ClienteViewAdapter(this.getActivity(), R.layout.fragment_cliente_item);
ListView lv = (ListView) view.findViewById(R.id.listaClientes);
lv.setVerticalFadingEdgeEnabled(true);
lv.setVerticalScrollBarEnabled(true);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TextView clienteId = (TextView) view.findViewById(R.id.clienteId);
TextView clienteNome = (TextView) view.findViewById(R.id.clienteNome);
TextView clienteTipoPessoa = (TextView) view.findViewById(R.id.clienteTipo);
Intent intent = new Intent(getActivity(), ContatosView.class);
//intent.putExtra("id_cliente", clienteId.getText()); // envia o id do cliente para a tela de detalhes
intent.putExtra("nome", clienteNome.getText());
intent.putExtra("tipo_pessoa", clienteTipoPessoa.getText());
startActivity(intent);
}
});
lv.setAdapter(ad);
} catch (Exception e) {
new AlertDialog.Builder(getActivity()).setTitle("Erro").setMessage(e.getMessage()).setNeutralButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
}).show();
}
return view;
}
private void gerarToast(CharSequence message) {
int duration = Toast.LENGTH_LONG;
Toast toast = Toast
.makeText(getActivity(), message, duration);
toast.show();
}
}
适配器:
public class ClienteViewAdapter extends ArrayAdapter<ClientesModel> {
private final LayoutInflater inflater;
private final int resourceId;
public ClienteViewAdapter(FragmentActivity context, int resource) {
super(context, resource);
this.inflater = LayoutInflater.from(context);
this.resourceId = resource;
}
@Override
public View getView(int position, View view, ViewGroup parent) {
ClientesModel cliente = getItem(position);
view = inflater.inflate(resourceId, parent, false);
//TextView tvId = (TextView) view.findViewById(R.id.txtTitle);
TextView tvNome = (TextView) view.findViewById(R.id.clienteNome);
TextView tvTipo = (TextView) view.findViewById(R.id.clienteTipo);
//tvId.setText(String.valueOf(cliente.ge()));
tvNome.setText(cliente.getNome());
tvTipo.setText(cliente.getTipo_pessoa());
return view;
}
}
Parsed Json:
public class ClientRest {
private RequestQueue mRequestQueue;
private ArrayList<ClientesModel> arrNews ;
public ArrayList<ClientesContatosModel> arrContatos ;
private Activity context;
public ClientRest(Activity ctx) {
this.context = ctx;
}
public interface ClientesRestListener {
public void clientesReceived(List<ClientesModel> clientes);
}
public final void getClientes(final ClientesRestListener listener) {
String url = "http://192.168.1.1/api/api/client/index.php";
// filtros
final ProgressDialog pDialog = new ProgressDialog(this.context);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setTitle("Sincronizando");
pDialog.setMessage("Aguarde...");
pDialog.show();
arrNews = new ArrayList<ClientesModel>();
arrContatos = new ArrayList<ClientesContatosModel>();
mRequestQueue = Volley.newRequestQueue(this.context);
JsonObjectRequest mJsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
List<ClientesModel> clientes = null;
try {
clientes = parseJSON(response);
pDialog.hide();
} catch (JSONException e) {
e.printStackTrace();
}
listener.clientesReceived(clientes);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (pDialog.isShowing()) {
pDialog.hide();
}
error.printStackTrace();
}
}
)
mRequestQueue.add(mJsonObjectRequest);
}
private List<ClientesModel> parseJSON(JSONObject json) throws JSONException {
try {
JSONArray dados = json.getJSONArray("dados");
for (int i = 0; i < dados.length(); i++) {
JSONObject item = dados.getJSONObject(i);
ClientesModel mClientesModel = new ClientesModel();
ClientesContatosModel mClientesContatoModel = new ClientesContatosModel();
/* cadastra os dados necessários no objeto no modelo */
mClientesModel.setId(item.optInt("id"));
mClientesModel.setNome(item.optString("nome"));
mClientesModel.setTipo_pessoa(item.optString("tipo_pessoa"));
mClientesModel.setInformacoes_adicionais(item.optString("informacoes_adicionais"));
mClientesModel.setCpf(item.optString("cpf"));
mClientesModel.setCnpj(item.optString("cnpj"));
JSONArray contatos = item.getJSONArray("contatos");
for (int j = 0; j < contatos.length(); j++) {
JSONObject data = contatos.getJSONObject(j);
mClientesContatoModel.setNome(data.optString("nome"));
mClientesContatoModel.setCargo(data.optString("cargo"));
}
arrNews.add(mClientesModel);
arrContatos.add(mClientesContatoModel);
}
} catch (Exception e) {
e.printStackTrace();
}
return arrNews;
}
}
答案 0 :(得分:4)
private ActionBar barra;
你必须在访问它之前初始化它
barra = getActionBar()
或
barra = getSupportActionBar()
如果您在前一种情况下使用系统ActionBar,或者在后一种情况下使用ActionBarCompat / ActionBarSherlock
答案 1 :(得分:1)
正如@blackbelt建议的那样,你必须在访问它之前初始化barra
,所以改变
**mTabsAdapter.addTab(barra.newTab().setIcon(R.drawable.clientes).setText(" Clientes"), ClienteActivity.class, null);**
barra = getSupportActionBar();
barra.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
到
barra = getSupportActionBar();
barra.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
**mTabsAdapter.addTab(barra.newTab().setIcon(R.drawable.clientes).setText(" Clientes"), ClienteActivity.class, null);**
答案 2 :(得分:1)
更改此代码
mViewPager = new ViewPager(this);
mViewPager.setId(R.id.pager);
setContentView(mViewPager);
mTabsAdapter = new TabsAdapter(this, mViewPager);
**mTabsAdapter.addTab(barra.newTab().setIcon(R.drawable.clientes).setText(" Clientes"), ClienteActivity.class, null);**
barra = getSupportActionBar();
barra.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
到
mViewPager = new ViewPager(this);
mViewPager.setId(R.id.pager);
setContentView(mViewPager);
barra = getSupportActionBar();
barra.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mTabsAdapter = new TabsAdapter(this, mViewPager);
**mTabsAdapter.addTab(barra.newTab().setIcon(R.drawable.clientes).setText(" Clientes"), ClienteActivity.class, null);**
希望这会有所帮助......