android code for nfc writer - java

hi this is my java file ......i m developing a nfc writer application.....here down is my java code file
package com.example.nfc_tag_writer;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.NfcAdapter.CreateNdefMessageCallback;
import android.nfc.NfcAdapter.OnNdefPushCompleteCallback;
import android.nfc.NfcEvent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;
import java.nio.charset.Charset;
public class SendTextViaNFCActivity extends Activity implements CreateNdefMessageCallback, OnNdefPushCompleteCallback {
private static final int MESSAGE_SENT = 1;
String CURSOR_HERE;
String SAVED_TEXT;
String beamText;
private final Handler mHandler;
NfcAdapter mNfcAdapter;
EditText myText;
class AnonymousClass_1 extends Handler {
final /* synthetic */ SendTextViaNFCActivity this$0;
AnonymousClass_1(SendTextViaNFCActivity r1_SendTextViaNFCActivity) {
super();
this$0 = r1_SendTextViaNFCActivity;
}
public void handleMessage(Message msg) {
switch(msg.what) {
case MESSAGE_SENT:
Toast.makeText(this$0.getApplicationContext(), "Message sent!", MESSAGE_SENT).show();
}
}
}
public SendTextViaNFCActivity() {
super();
SAVED_TEXT = "SAVED_TEXT";
CURSOR_HERE = "###CURSOR_HERE###";
beamText = "";
mHandler = new AnonymousClass_1(this);
}
public NdefRecord createMimeRecord(String mimeType, byte[] payload) {
return new NdefRecord((short) 2, mimeType.getBytes(Charset.forName("US-ASCII")), new byte[0], payload);
}
public NdefMessage createNdefMessage(NfcEvent event) {
NdefRecord[] r2_NdefRecord_A = new NdefRecord[2];
r2_NdefRecord_A[0] = createMimeRecord("application/com.example.android.beam", myText.getText().toString().getBytes());
r2_NdefRecord_A[1] = NdefRecord.createApplicationRecord("diewland.nfc.text");
return new NdefMessage(r2_NdefRecord_A);
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.send_text_via_nfc);
myText = (EditText) findViewById(R.id.my_text);
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (mNfcAdapter == null) {
myText.setText("NFC is not available on this device.");
myText.setEnabled(false);
}
mNfcAdapter.setNdefPushMessageCallback(this, this, new Activity[0]);
mNfcAdapter.setOnNdefPushCompleteCallback(this, this, new Activity[0]);
}
public boolean onCreateOptionsMenu(Menu menu) {
if (mNfcAdapter == null) {
return super.onCreateOptionsMenu(menu);
} else {
getMenuInflater().inflate(R.menu.options, menu);
return true;
}
}
public void onNdefPushComplete(NfcEvent arg0) {
mHandler.obtainMessage(MESSAGE_SENT).sendToTarget();
}
public void onNewIntent(Intent intent) {
setIntent(intent);
}
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.menu_settings:
startActivity(new Intent("android.settings.NFCSHARING_SETTINGS"));
return true;
case R.id.menu_reset:
myText.setText("");
return true;
case R.id.menu_share:
if (!"".equals(myText.getText().toString())) {
Intent sendIntent = new Intent();
sendIntent.setAction("android.intent.action.SEND");
sendIntent.putExtra("android.intent.extra.TEXT", myText.getText().toString());
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, "Share via"));
return true;
} else {
return true;
}
}
return super.onOptionsItemSelected(item);
}
protected void onPause() {
super.onPause();
myText.getText().insert(myText.getSelectionStart(), CURSOR_HERE);
Editor editor = getPreferences(0).edit();
editor.putString(SAVED_TEXT, myText.getText().toString());
editor.commit();
}
public void onResume() {
super.onResume();
Intent intent = getIntent();
String type = intent.getType();
if (!"android.intent.action.SEND".equals(intent.getAction()) || type == null) {
if ("android.nfc.action.NDEF_DISCOVERED".equals(getIntent().getAction())) {
processIntent(getIntent());
}
String restoredText = getPreferences(0).getString(SAVED_TEXT, null);
if (restoredText != null) {
myText.setText(restoredText.replaceAll(CURSOR_HERE, beamText));
}
} else if ("text/plain".equals(type)) {
myText.setText(intent.getStringExtra("android.intent.extra.TEXT"));
}
myText.setSelection(myText.getText().length());
}
void processIntent(Intent intent) {
beamText = new String(((NdefMessage) intent.getParcelableArrayExtra("android.nfc.extra.NDEF_MESSAGES")[0]).getRecords()[0].getPayload());
}
}
i m getting followings errorss
03-19 08:09:56.989: V/NFC(767): this device does not have NFC support
03-19 08:09:56.999: D/AndroidRuntime(767): Shutting down VM
03-19 08:09:56.999: W/dalvikvm(767): threadid=1: thread exiting with uncaught exception (group=0x414c4700)
03-19 08:09:57.029: E/AndroidRuntime(767): FATAL EXCEPTION: main
03-19 08:09:57.029: E/AndroidRuntime(767): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.nfc_tag_writer/com.example.nfc_tag_writer.SendTextViaNFCActivity}: java.lang.NullPointerException
03-19 08:09:57.029: E/AndroidRuntime(767): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
03-19 08:09:57.029: E/AndroidRuntime(767): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
03-19 08:09:57.029: E/AndroidRuntime(767): at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-19 08:09:57.029: E/AndroidRuntime(767): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
03-19 08:09:57.029: E/AndroidRuntime(767): at android.os.Handler.dispatchMessage(Handler.java:99)
03-19 08:09:57.029: E/AndroidRuntime(767): at android.os.Looper.loop(Looper.java:137)
03-19 08:09:57.029: E/AndroidRuntime(767): at android.app.ActivityThread.main(ActivityThread.java:5103)
03-19 08:09:57.029: E/AndroidRuntime(767): at java.lang.reflect.Method.invokeNative(Native Method)
03-19 08:09:57.029: E/AndroidRuntime(767): at java.lang.reflect.Method.invoke(Method.java:525)
03-19 08:09:57.029: E/AndroidRuntime(767): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
03-19 08:09:57.029: E/AndroidRuntime(767): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-19 08:09:57.029: E/AndroidRuntime(767): at dalvik.system.NativeStart.main(Native Method)
03-19 08:09:57.029: E/AndroidRuntime(767): Caused by: java.lang.NullPointerException
03-19 08:09:57.029: E/AndroidRuntime(767): at com.example.nfc_tag_writer.SendTextViaNFCActivity.onCreate(SendTextViaNFCActivity.java:75)
03-19 08:09:57.029: E/AndroidRuntime(767): at android.app.Activity.performCreate(Activity.java:5133)
03-19 08:09:57.029: E/AndroidRuntime(767): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
03-19 08:09:57.029: E/AndroidRuntime(767): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
03-19 08:09:57.029: E/AndroidRuntime(767): ... 11 more
please can anyone help me
i m getting the my errors in logcat...i m unable to fix them.....the app is unfornatelly stopping r crashing

Your checking that the mNfcAdapter is not null, yet still try to access it afterward even if it is. Try moving these lines
mNfcAdapter.setNdefPushMessageCallback(this, this, new Activity[0]);
mNfcAdapter.setOnNdefPushCompleteCallback(this, this, new Activity[0]);
into an else to the previous if:
if (mNfcAdapter == null) {
myText.setText("NFC is not available on this device.");
myText.setEnabled(false);
} else {
mNfcAdapter.setNdefPushMessageCallback(this, this, new Activity[0]);
mNfcAdapter.setOnNdefPushCompleteCallback(this, this, new Activity[0]);
}

Related

at com.example.u.locationtracker.MainActivity.onCreate(MainActivity.java:39)

I am new on android and working on my android app's login activity for which em using php mysql with volley library. But every time I run my app on emulator it shows the message Unfortunately, app has stopped. Here the login activity code is:
package com.example.u.locationtracker;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private EditText pass1, email1;
private Button login;
private TextView link_reg;
private ProgressBar loading;
private String URL_LOGIN= "http://192.168.1.1/register.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
email1= (EditText) findViewById(R.id.etemail1);
pass1= (EditText) findViewById(R.id.etpassl);
loading= (ProgressBar) findViewById(R.id.loading1);
link_reg= (TextView) findViewById(R.id.signup);
login= (Button) findViewById(R.id.btnlogin);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mEmail= email1.getText().toString().trim();
String mpass= pass1.getText().toString().trim();
if(!mEmail.isEmpty() || !mpass.isEmpty()){
Login(mEmail, mpass);
}else{
email1.setError("Please Enter Email...!");
pass1.setError("Please Enter Password...!");
}
}
});
link_reg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent it= new Intent(MainActivity.this, Register.class);
startActivity(it);
}
});
}
private void Login(final String email, final String pass) {
loading.setVisibility(View.VISIBLE);
login.setVisibility(View.GONE);
StringRequest stringRequest= new StringRequest(Request.Method.POST, URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
JSONObject jsonObject= new JSONObject(response);
String success= jsonObject.getString("Success");
JSONArray jsonArray= jsonObject.getJSONArray("Login");
if(success.equals("1")){
for (int i= 0; i < jsonArray.length(); i++){
JSONObject object= jsonArray.getJSONObject(i);
Toast t= Toast.makeText(MainActivity.this,
"Login Successful", Toast.LENGTH_LONG);
t.show();
loading.setVisibility(View.GONE);
}
}
}catch (JSONException e) {
e.printStackTrace();
loading.setVisibility(View.GONE);
login.setVisibility(View.VISIBLE);
Toast t1= Toast.makeText(MainActivity.this,
"Error" + e.toString(),
Toast.LENGTH_LONG);
t1.show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loading.setVisibility(View.GONE);
login.setVisibility(View.VISIBLE);
Toast t2= Toast.makeText(MainActivity.this,
"Error" + error.toString(),
Toast.LENGTH_LONG);
t2.show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params= new HashMap<>();
params.put("Email", email);
params.put("Password", pass);
return params;
}
};
RequestQueue requestQueue= Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
According to logcat the problem is:
at com.example.u.locationtracker.MainActivity.onCreate(MainActivity.java:39)
here the php code:
<?php
if ($_SERVER['REQUEST_METHOD']=='POST') {
$email= $_POST['email1'];
$pass= $_POST['pass1'];
require_once 'connect.php';
$select= "SELECT * FROM user_table WHERE Email= '$email' ";
$r= mysqli_query($conn, $select);
$result= array();
$result['login']= array();
if (mysqli_num_rows($r)=== 1) {
$row= mysqli_fetch_assoc($r);
if ( password_verify($pass, $row['Pass']) ) {
$index['Name']= $row['Name'];
$index['Email']= $row['Email'];
array_push($result['login'], $index);
$result['success']= "1";
$result['message']= "Success";
echo json_encode($result);
mysql_close($conn);
}else{
$result['success']= "0";
$result['message']= "Error";
echo json_encode($result);
mysql_close($conn);
}
}
}
?>
Here is the Logcat:
02-03 21:03:21.626 2006-2012/? E/jdwp: Failed writing handshake bytes: Broken pipe (-1 of 14)
02-03 21:03:21.806 2006-2006/? E/dalvikvm: Could not find class 'android.support.v4.view.ViewCompat$OnUnhandledKeyEventListenerWrapper', referenced from method android.support.v4.view.ViewCompat.addOnUnhandledKeyEventListener
02-03 21:03:21.806 2006-2006/? E/dalvikvm: Could not find class 'android.view.WindowInsets', referenced from method android.support.v4.view.ViewCompat.dispatchApplyWindowInsets
02-03 21:03:21.826 2006-2006/? E/dalvikvm: Could not find class 'android.view.WindowInsets', referenced from method android.support.v4.view.ViewCompat.onApplyWindowInsets
02-03 21:03:21.826 2006-2006/? E/dalvikvm: Could not find class 'android.view.View$OnUnhandledKeyEventListener', referenced from method android.support.v4.view.ViewCompat.removeOnUnhandledKeyEventListener
02-03 21:03:21.836 2006-2006/? E/dalvikvm: Could not find class 'android.support.v4.view.ViewCompat$1', referenced from method android.support.v4.view.ViewCompat.setOnApplyWindowInsetsListener
02-03 21:03:22.756 2006-2006/com.example.u.locationtracker E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering
02-03 21:03:27.786 2006-2006/com.example.u.locationtracker E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.u.locationtracker, PID: 2006
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.u.locationtracker/com.example.u.locationtracker.MainActivity}: android.view.InflateException: Binary XML file line #45: Error inflating class ImageView
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2193)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2243)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5019)
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)
Caused by: android.view.InflateException: Binary XML file line #45: Error inflating class ImageView
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:713)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at android.support.v7.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at com.example.u.locationtracker.MainActivity.onCreate(MainActivity.java:39)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2157)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2243) 
at android.app.ActivityThread.access$800(ActivityThread.java:135) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:136) 
at android.app.ActivityThread.main(ActivityThread.java:5019) 
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) 
Caused by: android.content.res.Resources$NotFoundException: Resource is not a Drawable (color or path): TypedValue{t=0x1/d=0x7f07005d a=-1 r=0x7f07005d}
at android.content.res.Resources.loadDrawable(Resources.java:2068)
at android.content.res.TypedArray.getDrawable(TypedArray.java:602)
at android.widget.ImageView.<init>(ImageView.java:129)
at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:72)
at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:68)
at android.support.v7.app.AppCompatViewInflater.createImageView(AppCompatViewInflater.java:182)
at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:106)
at android.support.v7.app.AppCompatDelegateImpl.createView(AppCompatDelegateImpl.java:1266)
at android.support.v7.app.AppCompatDelegateImpl.onCreateView(AppCompatDelegateImpl.java:1316)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:684)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755) 
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758) 
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758) 
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:492) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:397) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:353) 
at android.support.v7.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469) 
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140) 
at com.example.u.locationtracker.MainActivity.onCreate(MainActivity.java:39) 
at android.app.Activity.performCreate(Activity.java:5231) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2157) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2243) 
at android.app.ActivityThread.access$800(ActivityThread.java:135) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:136) 
at android.app.ActivityThread.main(ActivityThread.java:5019) 
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) 
The problem seems to lie in this line:
setContentView(R.layout.activity_main);
Are you sure, the layout exists and doesn't have compile errors?
A full stacktrace would be more helpful

Unable to start Activity Componentinfo (Adapter Constructor)

I tried to create a simple listview. I've done it many times & this is the first time i face such errors. Tried this in both Eclipse Luna & indigo. Both have the same error.
Here is where i create an instant of the adapter :
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
public class ActivityMain extends Activity {
public ArrayList<StructRemedy> remedies = new ArrayList<StructRemedy>();
private ListView lstContent;
public AdapterRemedy adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lstContent = (ListView) findViewById(R.id.lstContent);
adapter = new AdapterRemedy(remedies);
randomPopulation();
lstContent.setAdapter(adapter);
}
private void randomPopulation() {
for (int i = 0; i < 30; i++) {
StructRemedy remedy = new StructRemedy();
remedy.title = "Remedy" + i;
remedy.description = "Desc" + i;
remedy.rateValue = (float) (Math.random() * 5);
remedy.type = "tisane";
remedy.use = "Headaches";
remedies.add(remedy);
}
adapter.notifyDataSetChanged();
}
}
Now the error log (The error referes to the line where i create the constructor , u know the "super" line) :
06-08 10:03:27.875: E/AndroidRuntime(2715): FATAL EXCEPTION: main
06-08 10:03:27.875: E/AndroidRuntime(2715): java.lang.RuntimeException: Unable to start activity ComponentInfo{ahmad.azimi.app.herbal_remedies/test.test1.app.herbal_remedies.ActivityMain}: java.lang.NullPointerException
06-08 10:03:27.875: E/AndroidRuntime(2715): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
06-08 10:03:27.875: E/AndroidRuntime(2715): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
06-08 10:03:27.875: E/AndroidRuntime(2715): at android.app.ActivityThread.access$600(ActivityThread.java:141)
06-08 10:03:27.875: E/AndroidRuntime(2715): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
06-08 10:03:27.875: E/AndroidRuntime(2715): at android.os.Handler.dispatchMessage(Handler.java:99)
06-08 10:03:27.875: E/AndroidRuntime(2715): at android.os.Looper.loop(Looper.java:137)
06-08 10:03:27.875: E/AndroidRuntime(2715): at android.app.ActivityThread.main(ActivityThread.java:5041)
06-08 10:03:27.875: E/AndroidRuntime(2715): at java.lang.reflect.Method.invokeNative(Native Method)
06-08 10:03:27.875: E/AndroidRuntime(2715): at java.lang.reflect.Method.invoke(Method.java:511)
06-08 10:03:27.875: E/AndroidRuntime(2715): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-08 10:03:27.875: E/AndroidRuntime(2715): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
06-08 10:03:27.875: E/AndroidRuntime(2715): at dalvik.system.NativeStart.main(Native Method)
06-08 10:03:27.875: E/AndroidRuntime(2715): Caused by: java.lang.NullPointerException
06-08 10:03:27.875: E/AndroidRuntime(2715): at android.widget.ArrayAdapter.init(ArrayAdapter.java:310)
06-08 10:03:27.875: E/AndroidRuntime(2715): at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:153)
06-08 10:03:27.875: E/AndroidRuntime(2715): at test.test1.app.herbal_remedies.AdapterRemedy.<init>(AdapterRemedy.java:22)
06-08 10:03:27.875: E/AndroidRuntime(2715): at test.test1.app.herbal_remedies.ActivityMain.onCreate(ActivityMain.java:22)
06-08 10:03:27.875: E/AndroidRuntime(2715): at android.app.Activity.performCreate(Activity.java:5104)
06-08 10:03:27.875: E/AndroidRuntime(2715): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
06-08 10:03:27.875: E/AndroidRuntime(2715): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
This is the adapter :
import java.util.ArrayList;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
public class AdapterRemedy extends ArrayAdapter<StructRemedy> {
public AdapterRemedy(ArrayList<StructRemedy> remedies) {
super(G.context, R.layout.adapter_notes, remedies);
}
private static class ViewHolder {
public TextView txtTitle;
public TextView txtType;
public TextView txtFor;
public RatingBar rating;
public ViewGroup layoutRoot;
public ImageView imgLogo;
public ViewHolder(View view) {
layoutRoot = (ViewGroup) view.findViewById(R.id.layoutRoot);
txtTitle = (TextView) view.findViewById(R.id.txtTitle);
txtType = (TextView) view.findViewById(R.id.txtType);
txtFor = (TextView) view.findViewById(R.id.txtFor);
rating = (RatingBar) view.findViewById(R.id.rate);
imgLogo = (ImageView) view.findViewById(R.id.imgLogo);
}
public void fill(final ArrayAdapter<StructRemedy> adapter, final StructRemedy item, final int position) {
txtTitle.setText(item.title);
txtType.setText(item.type);
txtFor.setText(item.use);
rating.setRating(item.rateValue);
//imgLogo.setImageBitmap(bm);
layoutRoot.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(G.currentActivity, ActivitySelect.class);
intent.putExtra("POSITION", position);
G.currentActivity.startActivity(intent);
}
});
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
StructRemedy item = getItem(position);
if (convertView == null) {
convertView = G.inflater.inflate(R.layout.adapter_notes, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.fill(this, item, position);
return convertView;
}
}
Try this :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lstContent = (ListView) findViewById(R.id.lstContent);
randomPopulation();
}
Put adapter = new AdapterRemedy (remedies ) ; after randomPopulation. Or set adapter in randomPopulation method.
And remove adapter.notifyDataSetchanged() from randomPopulation.
Do some changes in your adapter code :
public AdapterRemedy(ArrayList<StructRemedy> remedies) {
super(G.context, R.layout.adapter_notes, remedies);
}
Change it to this :
public AdapterRemedy(context,ArrayList<StructRemedy> remedies) {
super(context, R.layout.adapter_notes, remedies);
}
And in randomPopulation :
adapter = new AdapterRemedy(this,remedies);
lstContent.setAdapter(adapter);
adapter.notifyDataSetChanged();
Change your onCreate() like ,
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lstContent = (ListView) findViewById(R.id.lstContent);
randomPopulation();
adapter = new AdapterRemedy(remedies);
lstContent.setAdapter(adapter);
}
Call randomPopulation() before the adater Initialization. remove
adapter.notifyDataSetChanged();

NullPointerException when scrolling ListView with images loaded from JSON

I've an error, when using ListView in Android, which is populated with images. Images urls are from tumblr JSON and android query loads them. Error message which I get is:
12-12 21:55:38.032 4334-4334/com.example.tumblrviewer E/InputEventReceiver﹕ Exception dispatching input event.
12-12 21:55:38.040 4334-4334/com.example.tumblrviewer D/dalvikvm﹕ GC_FOR_ALLOC freed 760K, 12% free 9993K/11292K, paused 5ms, total 6ms
12-12 21:55:38.040 4334-4334/com.example.tumblrviewer E/MessageQueue-JNI﹕ java.lang.NullPointerException
at com.example.tumblrviewer.MenuArrayAdapter.getView(MenuArrayAdapter.java:76)
at android.widget.AbsListView.obtainView(AbsListView.java:2161)
at android.widget.ListView.makeAndAddView(ListView.java:1840)
at android.widget.ListView.fillDown(ListView.java:675)
at android.widget.ListView.fillGap(ListView.java:639)
at android.widget.AbsListView.trackMotionScroll(AbsListView.java:4970)
at android.widget.AbsListView.onGenericMotionEvent(AbsListView.java:3680)
at android.view.View.dispatchGenericMotionEventInternal(View.java:7479)
at android.view.View.dispatchGenericMotionEvent(View.java:7460)
at android.view.ViewGroup.dispatchTransformedGenericPointerEvent(ViewGroup.java:1819)
at android.view.ViewGroup.dispatchGenericPointerEvent(ViewGroup.java:1772)
at android.view.View.dispatchGenericMotionEvent(View.java:7453)
at android.view.ViewGroup.dispatchTransformedGenericPointerEvent(ViewGroup.java:1819)
at android.view.ViewGroup.dispatchGenericPointerEvent(ViewGroup.java:1772)
at android.view.View.dispatchGenericMotionEvent(View.java:7453)
at android.view.ViewGroup.dispatchTransformedGenericPointerEvent(ViewGroup.java:1819)
at android.view.ViewGroup.dispatchGenericPointerEvent(ViewGroup.java:1772)
at android.view.View.dispatchGenericMotionEvent(View.java:7453)
at android.view.ViewGroup.dispatchTransformedGenericPointerEvent(ViewGroup.java:1819)
at android.view.ViewGroup.dispatchGenericPointerEvent(ViewGroup.java:1772)
at android.view.View.dispatchGenericMotionEvent(View.java:7453)
at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchGenericMotionEvent(PhoneWindow.java:1974)
at com.android.internal.policy.impl.PhoneWindow.superDispatchGenericMotionEvent(PhoneWindow.java:1428)
at android.app.Activity.dispatchGenericMotionEvent(Activity.java:2460)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchGenericMotionEvent(PhoneWindow.java:1928)
at android.view.View.dispatchPointerEvent(View.java:7566)
at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:3883)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:3778)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3429)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3398)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3483)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3406)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3540)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3429)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3398)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3406)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379)
at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:5419)
at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:5399)
at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:5370)
at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:5493)
at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:182)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:132)
at android.os.Looper.loop(Looper.java:124)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
12-12 21:55:38.044 4334-4334/com.example.tumblrviewer D/AndroidRuntime﹕ Shutting down VM
12-12 21:55:38.044 4334-4334/com.example.tumblrviewer W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xa4bd3648)
12-12 21:55:38.052 4334-4334/com.example.tumblrviewer E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.tumblrviewer.MenuArrayAdapter.getView(MenuArrayAdapter.java:76)
at android.widget.AbsListView.obtainView(AbsListView.java:2161)
at android.widget.ListView.makeAndAddView(ListView.java:1840)
at android.widget.ListView.fillDown(ListView.java:675)
at android.widget.ListView.fillGap(ListView.java:639)
at android.widget.AbsListView.trackMotionScroll(AbsListView.java:4970)
at android.widget.AbsListView.onGenericMotionEvent(AbsListView.java:3680)
at android.view.View.dispatchGenericMotionEventInternal(View.java:7479)
at android.view.View.dispatchGenericMotionEvent(View.java:7460)
at android.view.ViewGroup.dispatchTransformedGenericPointerEvent(ViewGroup.java:1819)
at android.view.ViewGroup.dispatchGenericPointerEvent(ViewGroup.java:1772)
at android.view.View.dispatchGenericMotionEvent(View.java:7453)
at android.view.ViewGroup.dispatchTransformedGenericPointerEvent(ViewGroup.java:1819)
at android.view.ViewGroup.dispatchGenericPointerEvent(ViewGroup.java:1772)
at android.view.View.dispatchGenericMotionEvent(View.java:7453)
at android.view.ViewGroup.dispatchTransformedGenericPointerEvent(ViewGroup.java:1819)
at android.view.ViewGroup.dispatchGenericPointerEvent(ViewGroup.java:1772)
at android.view.View.dispatchGenericMotionEvent(View.java:7453)
at android.view.ViewGroup.dispatchTransformedGenericPointerEvent(ViewGroup.java:1819)
at android.view.ViewGroup.dispatchGenericPointerEvent(ViewGroup.java:1772)
at android.view.View.dispatchGenericMotionEvent(View.java:7453)
at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchGenericMotionEvent(PhoneWindow.java:1974)
at com.android.internal.policy.impl.PhoneWindow.superDispatchGenericMotionEvent(PhoneWindow.java:1428)
at android.app.Activity.dispatchGenericMotionEvent(Activity.java:2460)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchGenericMotionEvent(PhoneWindow.java:1928)
at android.view.View.dispatchPointerEvent(View.java:7566)
at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:3883)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:3778)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3429)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3398)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3483)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3406)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3540)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3429)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3398)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3406)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379)
at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:5419)
at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:5399)
at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:5370)
at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:5493)
at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:182)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:132)
at android.os.Looper.loop(Looper.java:124)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
it points to MenuArrayAdapter line 76, which contains:
mAQ.id(viewHolder.mImageView).image(item.photos[0].photoUrl.uri, false, false, 600, 0, null, Constants.FADE_IN);
and I'm pretty sure this object is not null, because error occurs random, each time with different item in ArrayAdapter. It happens when I scroll ListView fast, up and down. I see that images does not have a time to load. Can it be related with a problem with memory? that there is too much data in the memory and app crashes? If so, what would be a good solution, if I want to stay with infinite scroll - I don't want to add "load more" button in the bottom, as e.g. Instagram does not have such button and it can load lots of images.
full code of this class is as follows:
package com.example.tumblrviewer;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.androidquery.util.Constants;
import com.example.tumblrviewer.model.HomeResponse;
import com.example.tumblrviewer.model.Item;
import org.json.JSONException;
import org.json.JSONObject;
public class MenuArrayAdapter extends ArrayAdapter<Item> {
private final LayoutInflater mInflater;
private final int mResourceId;
private AQuery mAQ;
private int postOffset;
public MenuArrayAdapter(Context context, int resource) {
super(context, resource);
mInflater = LayoutInflater.from(context);
mResourceId = resource;
mAQ = new AQuery(context);
postOffset=0;
//loadImages(postOffset);
}
public void setPosts(Item[] posts) {
//clear();
for (Item item : posts) {
add(item);
}
if (isEmpty()) {
notifyDataSetInvalidated();
} else {
notifyDataSetChanged();
}
}
#Override
public View getView(int i, View convertView, ViewGroup viewGroup) {
ViewHolder viewHolder = null;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = mInflater.inflate(mResourceId, viewGroup, false);
viewHolder.mImageView = (ImageView) convertView.findViewById(R.id.tumblr_photo_iv);
//viewHolder.mTagsLayout=(LinearLayout) convertView.findViewById(R.id.tags_layout);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
Item item = getItem(i);
//if ( item.photos[0].photoUrl.uri != null) {
mAQ.id(viewHolder.mImageView).image(item.photos[0].photoUrl.uri, false, false, 600, 0, null, Constants.FADE_IN);
//}
return convertView;
}
private class ViewHolder {
ImageView mImageView;
//LinearLayout mTagsLayout;
}
}
There is also main activity
package com.example.tumblrviewer;
import android.app.Activity;
import android.os.Bundle;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.example.tumblrviewer.model.HomeResponse;
import org.json.JSONException;
import org.json.JSONObject;
public class WeHaveTheMunchiesActivity extends Activity {
private AQuery mAQ;
private TextView mResultTextView;
private ListView mListView;
private MenuArrayAdapter mItemArrayAdapter;
private int postOffset;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_viewer);
mListView = (ListView) findViewById(R.id.items_lv);
mAQ = new AQuery(this);
mItemArrayAdapter = new MenuArrayAdapter(this, R.layout.item_on_list);
mListView.setAdapter(mItemArrayAdapter);
postOffset=0;
loadImages(postOffset);
mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView absListView, int i) {
}
#Override
public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
int lastItem = firstVisibleItem + visibleItemCount;
if(lastItem == totalItemCount ){
if(postOffset <= 10662
&& mListView.getChildAt(mListView.getChildCount() - 1) != null
&& mListView.getLastVisiblePosition() == mListView.getAdapter().getCount() - 1
&& mListView.getChildAt(mListView.getChildCount() - 1).getBottom() <= mListView.getHeight()) {
Toast.makeText(getApplicationContext(), "Bottom!", Toast.LENGTH_LONG).show();
loadImages(postOffset);
System.out.println("postOffset "+postOffset);
}
}
}
});
}
private void loadImages(int offset) {
String url = Constants.TUMBLR_API_BLOG_URL + Constants.TUMBLR_API_BLOG_HOSTNAME +
Constants.TUMBLR_API_CONTENT_TYPE + Constants.TUMBLR_API_KEY_NAME +
Constants.TUMBLR_API_KEY + "&offset=" + Integer.toString(offset);
AjaxCallback<JSONObject> cb = new AjaxCallback<JSONObject>();
cb.url(url).type(JSONObject.class).weakHandler(this, "itemsCallback");
mAQ.ajax(cb);
postOffset=postOffset+20;
}
public void itemsCallback(String url, JSONObject json, AjaxStatus status) throws JSONException {
//Toast.makeText(getApplicationContext(), status.getRedirect(), Toast.LENGTH_LONG).show();
//Toast.makeText(getApplicationContext(), status.getCode(), Toast.LENGTH_LONG).show();
//mResultTextView.setText(status.getMessage());
if (json != null) {
HomeResponse homeResponse = HomeResponse.fromJsonObject(json.getJSONObject("response"));
System.out.print(homeResponse.items);
mItemArrayAdapter.setPosts(homeResponse.items);
}
}
}

Application crashing because of NullPointerException

I'm working with a listview which on click opens a dialog box which contains an edittext and a button. On button click, the value entered in the editText is saved in a textView from listview item which had been pressed before. The problem is that the value wasn't saved anymore if I reopened the application. I tried to make it save using sharedPrefences but it's crashing and shows 3 nullpointerexception and can't deal with them.
Here is my:
Carnet.java
package com.cngcnasaud.orar;
import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
#SuppressWarnings("deprecation")
public class Carnet extends TabActivity {
// TabSpec Names
private static final String NOTA_SPEC = "Note";
private static final String ABSENTE_SPEC = "Absente";
private static final String MEDII_SPEC = "Medii";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.carnet);
TabHost tabHost = getTabHost();
TabSpec NotaSpec = tabHost.newTabSpec(NOTA_SPEC);
// Tab Icon
NotaSpec.setIndicator(NOTA_SPEC, getResources().getDrawable(R.drawable.nota_open));
Intent notaIntent = new Intent(this, Note.class);
// Tab Content
NotaSpec.setContent(notaIntent);
TabSpec AbsenteSpec = tabHost.newTabSpec(ABSENTE_SPEC);
AbsenteSpec.setIndicator(ABSENTE_SPEC, getResources().getDrawable(R.drawable.nota_open));
Intent absenteIntent = new Intent(this, Absente.class);
AbsenteSpec.setContent(absenteIntent);
TabSpec MediiSpec = tabHost.newTabSpec(MEDII_SPEC);
AbsenteSpec.setIndicator(MEDII_SPEC, getResources().getDrawable(R.drawable.nota_open));
Intent mediiIntent = new Intent(this, MediiL.class);
AbsenteSpec.setContent(mediiIntent);
// Adding all TabSpec to TabHost
tabHost.addTab(NotaSpec);
tabHost.addTab(AbsenteSpec);
tabHost.addTab(MediiSpec);
}
}
Note.java
package com.cngcnasaud.orar;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.Menu;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class Note extends Activity {
private static final ListAdapter NoteAdapter = null;
ListView lv;
Context context;
ArrayList<?> prgmName;
TextView text;
public static String[] prgmNameList = { "Romana - ", "Matematica - ",
"Lb. Engleza - ", "Lb. Germana/Franceza - ", "Istorie - ",
"Geografie - ", "Biologie - ", "Fizica - ", "Ed. Fizica - " };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.note_listview);
text = (TextView) findViewById(R.id.textView2);
context = this;
lv = (ListView) findViewById(R.id.listView);
lv.setAdapter(new NoteAdapter(this, prgmNameList, null));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
NoteAdapter adapter = (NoteAdapter) lv.getAdapter();
// Variable is public for clarity.
String toSave = EncodeDecode.encode(adapter.savedEntries);
SharedPreferences.Editor editor = getSharedPreferences("LV Data",
MODE_PRIVATE).edit();
editor.putString("TVEntries", toSave);
editor.commit();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
SharedPreferences prefs = getSharedPreferences("LV Data", MODE_PRIVATE);
String encoded = prefs.getString("TVEntries", "");
String[] entries;
if (encoded.equals(""))
entries = null;
else
entries = EncodeDecode.decode(encoded);
NoteAdapter adapter = (NoteAdapter) lv.getAdapter();
adapter.savedEntries = entries;
lv.setAdapter(adapter);
super.onResume();
}
}
And NoteAdapter.java:
package com.cngcnasaud.orar;
import java.util.Arrays;
import android.app.Dialog;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
public class NoteAdapter extends BaseAdapter {
String[] result;
Context context;
int[] imageId;
private static LayoutInflater inflater = null;
private Dialog dialog;
String[] savedEntries;
String[] saved = null;
public NoteAdapter(Note note, String[] saved, String[] prgmNameList) {
// TODO Auto-generated constructor stub
result = prgmNameList;
context = note;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (saved == null) {
savedEntries = new String[result.length];
Arrays.fill(savedEntries, "");
} else
savedEntries = saved;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return result.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return savedEntries[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder {
TextView tv;
ImageView img;
public TextView text;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final Holder holder = new Holder();
View rowView;
rowView = inflater.inflate(R.layout.note_items, null);
holder.tv = (TextView) rowView.findViewById(R.id.textView1);
holder.text = (TextView) rowView.findViewById(R.id.textView2);
holder.text.setText(savedEntries[position]);
holder.img = (ImageView) rowView.findViewById(R.id.imageView1);
rowView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog = new Dialog(context);
dialog.setContentView(R.layout.dialog);
dialog.setTitle("Materie:" + result[position]);
final EditText txtMode = (EditText) dialog
.findViewById(R.id.dialog);
Button btnSave = (Button) dialog.findViewById(R.id.bsave);
btnSave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String data = txtMode.getText().toString();
holder.text.setText(data);
savedEntries[position] = data;
dialog.dismiss();
Log.d("data", data);
}
});
dialog.show();
}
});
return rowView;
}
}
logcat:
04-18 19:27:28.558: E/AndroidRuntime(1419): FATAL EXCEPTION: main
04-18 19:27:28.558: E/AndroidRuntime(1419): Process: com.cngcnasaud.orar, PID: 1419
04-18 19:27:28.558: E/AndroidRuntime(1419): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.cngcnasaud.orar/com.cngcnasaud.orar.Carnet}: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.cngcnasaud.orar/com.cngcnasaud.orar.Note}: java.lang.NullPointerException
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.ActivityThread.access$800(ActivityThread.java:135)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.os.Handler.dispatchMessage(Handler.java:102)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.os.Looper.loop(Looper.java:136)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-18 19:27:28.558: E/AndroidRuntime(1419): at java.lang.reflect.Method.invokeNative(Native Method)
04-18 19:27:28.558: E/AndroidRuntime(1419): at java.lang.reflect.Method.invoke(Method.java:515)
04-18 19:27:28.558: E/AndroidRuntime(1419): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-18 19:27:28.558: E/AndroidRuntime(1419): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-18 19:27:28.558: E/AndroidRuntime(1419): at dalvik.system.NativeStart.main(Native Method)
04-18 19:27:28.558: E/AndroidRuntime(1419): Caused by: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.cngcnasaud.orar/com.cngcnasaud.orar.Note}: java.lang.NullPointerException
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.ActivityThread.startActivityNow(ActivityThread.java:2035)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:135)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:347)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:749)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.widget.TabHost.setCurrentTab(TabHost.java:413)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.widget.TabHost.addTab(TabHost.java:240)
04-18 19:27:28.558: E/AndroidRuntime(1419): at com.cngcnasaud.orar.Carnet.onCreate(Carnet.java:45)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.Activity.performCreate(Activity.java:5231)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
04-18 19:27:28.558: E/AndroidRuntime(1419): ... 11 more
04-18 19:27:28.558: E/AndroidRuntime(1419): Caused by: java.lang.NullPointerException
04-18 19:27:28.558: E/AndroidRuntime(1419): at com.cngcnasaud.orar.NoteAdapter.getCount(NoteAdapter.java:46)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.widget.ListView.setAdapter(ListView.java:480)
04-18 19:27:28.558: E/AndroidRuntime(1419): at com.cngcnasaud.orar.Note.onCreate(Note.java:34)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.Activity.performCreate(Activity.java:5231)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
04-18 19:27:28.558: E/AndroidRuntime(1419): ... 21 more
Carnet.java line 45:
tabHost.addTab(NotaSpec);
NoteAdapter.java line 46:
return result.length;
Note.java line 34:
lv.setAdapter(new NoteAdapter(this, prgmNameList, null));
Your String array in null here:
NoteAdapter.java line 46:
return result.length;
because is a class field, you populate in the constructor from a parameter:
public NoteAdapter(Note note, String[] saved, String[] prgmNameList) {
// TODO Auto-generated constructor stub
result = prgmNameList;
that you pass as null here (passed as second parameter, it should be third):
Note.java line 34:
lv.setAdapter(new NoteAdapter(this, prgmNameList, null));
There is no point in passing that as a parameter as it is a public constant (public static final).

Error in android.os.Process.killProcess(android.os.Process.myPid());

Ive got an error when i call this android.os.Process.killProcess(android.os.Process.myPid());
My logcat says it is unable to start activity. as my understanding using kill process is to kill task that is running but when i use this it shows that it is starting to call another activity.
here is my code:
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(S_2nd_LoginActivity.this);
alertDialogBuilder.setTitle("Are you sure you want to cancel?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
android.os.Process.killProcess(android.os.Process.myPid());
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
here is my logcat:
03-04 18:28:43.805: E/AndroidRuntime(19417): java.lang.RuntimeException: Unable to start activity ComponentInfo{ph.com.example.Project/ph.com.example.Project.MainActivity}: java.lang.NullPointerException
03-04 18:28:43.805: E/AndroidRuntime(19417): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1815)
03-04 18:28:43.805: E/AndroidRuntime(19417): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1831)
03-04 18:28:43.805: E/AndroidRuntime(19417): at android.app.ActivityThread.access$500(ActivityThread.java:122)
03-04 18:28:43.805: E/AndroidRuntime(19417): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1024)
03-04 18:28:43.805: E/AndroidRuntime(19417): at android.os.Handler.dispatchMessage(Handler.java:99)
03-04 18:28:43.805: E/AndroidRuntime(19417): at android.os.Looper.loop(Looper.java:132)
03-04 18:28:43.805: E/AndroidRuntime(19417): at android.app.ActivityThread.main(ActivityThread.java:4123)
03-04 18:28:43.805: E/AndroidRuntime(19417): at java.lang.reflect.Method.invokeNative(Native Method)
03-04 18:28:43.805: E/AndroidRuntime(19417): at java.lang.reflect.Method.invoke(Method.java:491)
03-04 18:28:43.805: E/AndroidRuntime(19417): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:844)
03-04 18:28:43.805: E/AndroidRuntime(19417): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
03-04 18:28:43.805: E/AndroidRuntime(19417): at dalvik.system.NativeStart.main(Native Method)
03-04 18:28:43.805: E/AndroidRuntime(19417): Caused by: java.lang.NullPointerException
03-04 18:28:43.805: E/AndroidRuntime(19417): at ph.com.example.Project.MainActivity.get_Territory(MainActivity.java:169)
03-04 18:28:43.805: E/AndroidRuntime(19417): at ph.com.example.Project.MainActivity.onCreate(MainActivity.java:74)
03-04 18:28:43.805: E/AndroidRuntime(19417): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1050)
03-04 18:28:43.805: E/AndroidRuntime(19417): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1779)
here is my method of get Territory:
public void get_Territory() {
String territory = String.valueOf(LoginActivity.g_territory);
lbl_user.setText(LoginActivity.txt_username.getText().toString());
String s = l_databaseHandler.get_territoryCode(territory);
String f = l_databaseHandler.get_doctorFname(s);
String l = l_databaseHandler.get_doctorLname(s);
Cursor cursorAllDetails = l_databaseHandler.get_all_sameDoctorname(f, l);
if (cursorAllDetails.getCount() != 0){
fillData(cursorAllDetails);
}else{
save_territory();
}
}
and i call this method this way on my onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
l_databaseHandler = new DatabaseHandler(this);
if (l_databaseHandler != null) {
l_databaseHandler.close();
l_databaseHandler.createDB();
}
Constants.from_add = false;
Constants.from_edit = false;
Constants.from_view = false;
cast_views();
get_Territory();
log_out();
}
Any help will be appreciated, thank you. I'd use this before and i use it again the same way, i just dont get it why it is acting this way.
TRy like this
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(S_2nd_LoginActivity.this);
alertDialogBuilder.setTitle("Are you sure you want to cancel?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
And in your onDestroy() method call android.os.Process.killProcess(android.os.Process.myPid());
EditText txt_username;
TextView lbl_user;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt_username= (EditText)findViewById(R.id.yourEditTextId);
lbl_user= (TextView )findViewById(R.id.yourTextViewId);
l_databaseHandler = new DatabaseHandler(this);
if (l_databaseHandler != null) {
l_databaseHandler.close();
l_databaseHandler.createDB();
}
Constants.from_add = false;
Constants.from_edit = false;
Constants.from_view = false;
cast_views();
get_Territory();
log_out();
}
try using this.
String name = LoginActivity.txt_username.getText().toString();
if(name != null)
lbl_user.setText(name);
else
lbl_user.setText("");

Categories

Resources