error in android application ArrayList - java

Hello how are you? I'm creating an android app news and is working very well, the only problem is when I'm doing the reading of the text and minimize the app to do something else and then return the app presents this error.
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: FATAL EXCEPTION: main
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: at java.util.ArrayList.get(ArrayList.java:304)
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: at com.brfgd.ActivityDetailStory.setAdapterToListview(ActivityDetailStory.java:179)
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: at com.brfgd.ActivityDetailStory$MyTask.onPostExecute(ActivityDetailStory.java:171)
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: at com.brfgd.ActivityDetailStory$MyTask.onPostExecute(ActivityDetailStory.java:119)
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: at android.os.AsyncTask.finish(AsyncTask.java:631)
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: at android.os.AsyncTask.access$600(AsyncTask.java:177)
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:99)
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: at android.os.Looper.loop(Looper.java:153)
part of the error
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class ActivityDetailStory extends AppCompatActivity {
int position;
String str_cid, str_cat_id, str_cat_image, str_cat_name, str_title, str_image, str_desc, str_date;
TextView news_title, news_date;
WebView news_desc;
ImageView img_news, img_fav;
DatabaseHandler db;
List<ItemStoryList> arrayOfRingcatItem;
ItemStoryList objAllBean;
final Context context = this;
ProgressBar progressBar;
LinearLayout content;
private AdView mAdView;
private InterstitialAd interstitial;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_story);
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final android.support.v7.app.ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(Constant.CATEGORY_TITLE);
}
//show admob banner ad
mAdView = (AdView) findViewById(R.id.adView);
mAdView.loadAd(new AdRequest.Builder().build());
mAdView.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
}
#Override
public void onAdFailedToLoad(int error) {
mAdView.setVisibility(View.GONE);
}
#Override
public void onAdLeftApplication() {
}
#Override
public void onAdOpened() {
}
#Override
public void onAdLoaded() {
mAdView.setVisibility(View.VISIBLE);
}
});
content = (LinearLayout) findViewById(R.id.content);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
img_fav = (FloatingActionButton) findViewById(R.id.img_fav);
img_news = (ImageView) findViewById(R.id.image);
news_title = (TextView) findViewById(R.id.title);
news_date = (TextView) findViewById(R.id.subtitle);
news_desc = (WebView) findViewById(R.id.desc);
db = new DatabaseHandler(ActivityDetailStory.this);
arrayOfRingcatItem = new ArrayList<ItemStoryList>();
//imageLoader = new ImageLoader(ActivityDetailStory.this);
if (JsonUtils.isNetworkAvailable(ActivityDetailStory.this)) {
new MyTask().execute(Constant.SERVER_URL + "/api.php?nid=" + Constant.NEWS_ITEMID);
MyApplication.getInstance().trackScreenView("Lendo de cara : " + (Constant.CATEGORY_TITLE));
}
else {
Toast.makeText(getApplicationContext(), "Problema com sua Rede de Internet", Toast.LENGTH_SHORT).show();
}
}
private class MyTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(String... params) {
return JsonUtils.getJSONString(params[0]);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressBar.setVisibility(View.GONE);
content.setVisibility(View.VISIBLE);
if (null == result || result.length() == 0) {
Toast.makeText(getApplicationContext(), "Problema com sua Rede de Internet!", Toast.LENGTH_SHORT).show();
} else {
try {
JSONObject mainJson = new JSONObject(result);
JSONArray jsonArray = mainJson.getJSONArray(Constant.CATEGORY_ARRAY_NAME);
JSONObject objJson = null;
for (int i = 0; i < jsonArray.length(); i++) {
objJson = jsonArray.getJSONObject(i);
ItemStoryList objItem = new ItemStoryList();
objItem.setCId(objJson.getString(Constant.CATEGORY_ITEM_CID));
objItem.setCategoryName(objJson.getString(Constant.CATEGORY_ITEM_NAME));
objItem.setCategoryImage(objJson.getString(Constant.CATEGORY_ITEM_IMAGE));
objItem.setCatId(objJson.getString(Constant.CATEGORY_ITEM_CAT_ID));
objItem.setNewsImage(objJson.getString(Constant.CATEGORY_ITEM_NEWSIMAGE));
objItem.setNewsHeading(objJson.getString(Constant.CATEGORY_ITEM_NEWSHEADING));
objItem.setNewsDescription(objJson.getString(Constant.CATEGORY_ITEM_NEWSDESCRI));
objItem.setNewsDate(objJson.getString(Constant.CATEGORY_ITEM_NEWSDATE));
arrayOfRingcatItem.add(objItem);
}
} catch (JSONException e) {
e.printStackTrace();
}
setAdapterToListview();
}
}
}
public void setAdapterToListview() {
//if(arrayOfRingcatItem.size()>0) {
objAllBean = arrayOfRingcatItem.get(0);
str_cid = objAllBean.getCId();
str_cat_name = objAllBean.getCategoryName();
str_cat_image = objAllBean.getCategoryImage();
str_cat_id = objAllBean.getCatId();
str_title = objAllBean.getNewsHeading();
str_desc = objAllBean.getNewsDescription();
str_image = objAllBean.getNewsImage();
str_date = objAllBean.getNewsDate();
news_title.setText(str_title);
news_date.setText(str_date);
news_desc.setBackgroundColor(Color.parseColor("#FFFFFF"));
news_desc.setFocusableInTouchMode(false);
news_desc.setFocusable(false);
news_desc.getSettings().setDefaultTextEncodingName("UTF-8");
WebSettings webSettings = news_desc.getSettings();
Resources res = getResources();
int fontSize = res.getInteger(R.integer.font_size);
webSettings.setDefaultFontSize(fontSize);
String mimeType = "text/html; charset=UTF-8";
String encoding = "utf-8";
String htmlText = str_desc;
String text = "<html><head><style type=\"text/css\">#font-face {font-family: MyFont;src: url(\"file:///android_asset/Roboto-Light.ttf\")}body {font-family: MyFont;font-size: medium; color: #525252;}</style></head><body>"
+ htmlText + "</body></html>";
news_desc.loadData(text, mimeType, encoding);
List<Pojo> pojolist = db.getFavRow(str_cat_id);
if (pojolist.size() == 0) {
img_fav.setImageResource(R.drawable.ic_bookmark_outline);
} else {
if (pojolist.get(0).getCatId().equals(str_cat_id))
;
{
img_fav.setImageResource(R.drawable.ic_bookmark_white);
}
}
img_fav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
List<Pojo> pojolist = db.getFavRow(str_cat_id);
if (pojolist.size() == 0) {
db.AddtoFavorite(new Pojo(str_cat_id, str_cid, str_cat_name, str_title, str_image, str_desc, str_date));
Toast.makeText(getApplicationContext(), "Leitura Marcada", Toast.LENGTH_SHORT).show();
img_fav.setImageResource(R.drawable.ic_bookmark_white);
interstitial = new InterstitialAd(ActivityDetailStory.this);
interstitial.setAdUnitId(getString(R.string.admob_interstitial_id));
AdRequest adRequest = new AdRequest.Builder().build();
interstitial.loadAd(adRequest);
interstitial.setAdListener(new AdListener() {
public void onAdLoaded() {
if (interstitial.isLoaded()) {
interstitial.show();
}
}
});
} else {
if (pojolist.get(0).getCatId().equals(str_cat_id)) {
db.RemoveFav(new Pojo(str_cat_id));
Toast.makeText(getApplicationContext(), "Leitura desmarcada!", Toast.LENGTH_SHORT).show();
img_fav.setImageResource(R.drawable.ic_bookmark_outline);
}
}
}
});
//}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_story, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
onBackPressed();
break;
case R.id.menu_share:
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Estou lendo vários livro com esse app estou adorando, baixe já, Recomendo "+"https://play.google.com/store/apps/details?id="+getPackageName());
sendIntent.setType("text/plain");
startActivity(sendIntent);
break;
default:
return super.onOptionsItemSelected(menuItem);
}
return true;
}
#Override
protected void onPause() {
// mAdView.pause();
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
//mAdView.resume();
}
#Override
protected void onDestroy() {
//mAdView.destroy();
super.onDestroy();
}
}

You should do this:
public void setAdapterToListview() {
if(arrayOfRingcatItem.size>0){
objAllBean = arrayOfRingcatItem.get(0);
str_cid = objAllBean.getCId();
str_cat_name = objAllBean.getCategoryName();
}
}
EDIT: onResume()
#Override
protected void onResume(){
super.onResume();
arrayOfRingcatItem = new ArrayList<ItemStoryList>();
//imageLoader = new ImageLoader(ActivityDetailStory.this);
if (JsonUtils.isNetworkAvailable(ActivityDetailStory.this)) {
new MyTask().execute(Constant.SERVER_URL + "/api.php?nid=" + Constant.NEWS_ITEMID);
MyApplication.getInstance().trackScreenView("Lendo de cara : " + (Constant.CATEGORY_TITLE));
}
else {
Toast.makeText(getApplicationContext(), "Problema com sua Rede de Internet", Toast.LENGTH_SHORT).show();
}
}
Or you can save the array in the Application class and use it from there, or in a singleton. The error it's because when the activity go to background Android can release some memory and delete your array.
EDIT 2: You can use SharedPreferences to save the id.
You have to put this code in onCreate:
SharedPreferences opc=getSharedPreferences("AppName", 0);
SharedPreferences.Editor editor =opc.edit();
editor.putInt("ID_SAVED",NEWS_ITEMID); editor.commit();
And in the onResume:
SharedPreferences opc=getSharedPreferences("AppName", 0);
NEWS_ITEMID=opc.getInt("ID_SAVED", -1);

Based on what you stated above everything is working fine except:
minimize the app to do something else and then return the app presents this error
You may need to reinitialize code in:
#Override
public void onResume(){
super.onResume();
// put your code here to repopulate arraylist...
refreshMyData();
}
refreshMyData could have:
public void refreshMyData(){
if (JsonUtils.isNetworkAvailable(ActivityDetailStory.this)) {
new MyTask().execute(Constant.SERVER_URL + "/api.php?nid=" + Constant.NEWS_ITEMID);
MyApplication.getInstance().trackScreenView("Lendo de cara : " + (Constant.CATEGORY_TITLE));
}else {
Toast.makeText(getApplicationContext(), "Problema com sua Rede de Internet", Toast.LENGTH_SHORT).show();
}
}
Use this method in your oncreate as well, that way you can have the same method call when creating the activity and resuming.
Sources:
How to use onResume()?

Related

Attempt to invoke virtual method 'void android.view.View.setAlpha(float) [duplicate]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have an Android app. This app has 12 activities, the first activity is the Splash Screen and sec activity is the intropage and 3rd activity is main and etc When I run the app, it doesn't enter the main activity and the app closes. The error is as follows:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setAlpha(float)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setAlpha(float)' on a null object reference
at com.github.hujiaweibujidao.wava.BaseViewAnimator.reset(BaseViewAnimator.java:78)
at com.github.hujiaweibujidao.wava.BaseViewAnimator.start(BaseViewAnimator.java:55)
at com.github.hujiaweibujidao.wava.YoYo$Builder.start(YoYo.java:128)
at com.github.hujiaweibujidao.wava.YoYo$Builder.playOn(YoYo.java:115)
at com.example.myapplication.MainActivity.onCreate(MainActivity.java:108)
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6119) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Thank you for your answers, but the solutions you gave me did not help. I checked, but it still gave me the same error. I put three-activated codes for you. Can you help me, please?
this my main activity java code:
package com.example.myapplication;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.Settings;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.akshay.library.CurveBottomBar;
import com.github.hujiaweibujidao.wava.Techniques;
import com.github.hujiaweibujidao.wava.YoYo;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;
import com.mxn.soul.flowingdrawer_core.ElasticDrawer;
import com.mxn.soul.flowingdrawer_core.FlowingDrawer;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import uk.co.samuelwall.materialtaptargetprompt.MaterialTapTargetPrompt;
public class MainActivity extends AppCompatActivity {
CurveBottomBar cbb;
FlowingDrawer mDrawer;
ImageView img_icon,imgtest,img_music,img_night,img_main,img_setting;
TextView txt;
String patch;
boolean read=false,music=true,night_mode;
Button btn_fehrest,btn_last_story,btn_fav;
SharedPreferences sharedP;
LinearLayout lin_main;
Toast exit;
boolean show_intropage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cbb = findViewById(R.id.cbb);
mDrawer = findViewById(R.id.drawerlayout);
img_icon = findViewById(R.id.img_icon);
imgtest = findViewById(R.id.imgtest);
txt = findViewById(R.id.txt);
btn_fehrest = findViewById(R.id.btn_fehrest);
img_music = findViewById(R.id.img_music);
lin_main = findViewById(R.id.lin_main);
img_night = findViewById(R.id.img_night);
img_main = findViewById(R.id.img_main);
btn_last_story = findViewById(R.id.btn_last_story);
btn_fav = findViewById(R.id.btn_fav);
img_setting = findViewById(R.id.img_setting);
cbb.inflateMenu(R.menu.menu_scrolling);
sharedP = getSharedPreferences(Items.SETTINGS, Context.MODE_PRIVATE);
show_intropage = sharedP.getBoolean(Items.INTROPAGE,true);
cbb.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.img_setting:
// kary ke mikhaym anjam bedim
break;
case R.id.img_music:
//
break;
}
return false;
}
});
YoYo.with(Techniques.ZoomInDown).duration(1000).playOn(btn_fehrest);
YoYo.with(Techniques.ZoomInDown).duration(1000).playOn(btn_last_story);
YoYo.with(Techniques.ZoomInDown).duration(1000).playOn(btn_fav);
YoYo.with(Techniques.ZoomInDown).duration(1000).playOn(img_music);
YoYo.with(Techniques.ZoomInDown).duration(1000).playOn(img_setting);
get_night();
permission();
//createFile();
if (show_intropage){
taptarget();
}
img_icon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDrawer.openMenu(true);
}
});
mDrawer.setTouchMode(ElasticDrawer.TOUCH_MODE_BEZEL);
mDrawer.setBackgroundColor(Color.WHITE);
mDrawer.setOnDrawerStateChangeListener(new ElasticDrawer.OnDrawerStateChangeListener() {
#Override
public void onDrawerStateChange(int oldState, int newState) {
if (newState == ElasticDrawer.STATE_CLOSED) {
Log.i("MainActivity", "Drawer STATE_CLOSED");
}
}
#Override
public void onDrawerSlide(float openRatio, int offsetPixels) {
Log.i("MainActivity", "openRatio=" + openRatio + " ,offsetPixels=" + offsetPixels);
}
});
}
public void createFile(){
try {
patch = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Mbook/";
File mfile = new File(patch);
if (!mfile.exists()) {
mfile.mkdir();
mfile.createNewFile();
CopyDB(getBaseContext().getAssets().open("Mbook.db"), new FileOutputStream(patch+"/Mbook.db"));
//Toast.makeText(this, patch+"", Toast.LENGTH_LONG).show();
}
}catch (FileNotFoundException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
public void CopyDB (InputStream inputStream, OutputStream outputStream) throws IOException {
byte[] buffer = new byte[1024];
int file_length;
while ((file_length = inputStream.read(buffer))>0){
outputStream.write(buffer,0,file_length);
}
inputStream.close();
outputStream.close();
}
public void fehrest_intent(View view) {
mDrawer.closeMenu(true);
YoYo.with(Techniques.Pulse).duration(800).playOn(btn_fehrest);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(getBaseContext(), Fehrest.class);
intent.putExtra("button","fehrest");
startActivity(intent);
}
},1500);
}
private void permission(){
Dexter.withContext(MainActivity.this)
.withPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse response) {
createFile();
}
#Override
public void onPermissionDenied(PermissionDeniedResponse response) {
if (response !=null && response.isPermanentlyDenied()){
AlertDialog.Builder Hoshdar = new AlertDialog.Builder(MainActivity.this);
Hoshdar.setMessage("جهت استفاده از برنامه دادن اجازه دسترسی ضروریست");
Hoshdar.setCancelable(false);
Hoshdar.setPositiveButton("رفتن به تنظیمات", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.fromParts("package",getPackageName(),null));
startActivity(intent);
}
});
}
Toast.makeText(MainActivity.this, "جهت استفاده از برنامه دادن اجازه دسترسی ضروریست", Toast.LENGTH_SHORT).show();
alert();
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, final PermissionToken token) {
alert();
}
}).check();
}
public void alert(){
AlertDialog.Builder Hoshdar = new AlertDialog.Builder(MainActivity.this);
Hoshdar.setTitle("توجه");
Hoshdar.setMessage("جهت استفاده از برنامه دادن اجازه دسترسی ضروریست لطفا درقسمت تنظیمات اجازه دسترسی را فعال کنید");
Hoshdar.setCancelable(false);
Hoshdar.setPositiveButton("رفتن به تنظیمات", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.fromParts("package",getPackageName(),null));
startActivity(intent);
}
});
Hoshdar.create().show();
}
public void fav_intent(View view) {
YoYo.with(Techniques.Pulse).duration(600).playOn(btn_fav);
mDrawer.closeMenu(true);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(getBaseContext(), Fehrest.class);
intent.putExtra("button","fav");
intent.putExtra("activity","main");
startActivity(intent);
}
},1500);
}
public void text_intent(View view) {
YoYo.with(Techniques.Pulse).duration(600).playOn(btn_last_story);
if (read){
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent_movies = new Intent(getBaseContext(), Text_activity.class);
intent_movies.putExtra("activity","main");
startActivity(intent_movies);
}
},1500);
}else {
Toast.makeText(this, "هنوز هیچ داستانی مطالعه نکردید!", Toast.LENGTH_SHORT).show();
}
}
public void setting_intent(MenuItem item) {
mDrawer.closeMenu(true);
YoYo.with(Techniques.Pulse).duration(600).playOn(img_setting);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(MainActivity.this,Setting.class));
}
},1500);
}
public void set_music(MenuItem item) {
YoYo.with(Techniques.Pulse).duration(600).playOn(img_music);
if (music){
stopService(new Intent(MainActivity.this,PlayMusic.class));
img_music.setBackgroundResource(R.drawable.music_off_icon);
music=false;
sharedP.edit().putBoolean(Items.MUSIC, false).apply();
}else {
startService(new Intent(MainActivity.this,PlayMusic.class));
img_music.setBackgroundResource(R.drawable.music_on_icon);
music=true;
sharedP.edit().putBoolean(Items.MUSIC, true).apply();
}
}
public void get_night(){
music = sharedP.getBoolean(Items.MUSIC,true);
night_mode = sharedP.getBoolean(Items.NIGHT_MODE,false);
read = sharedP.getBoolean(Items.READ,false);
if (night_mode){
lin_main.setBackgroundResource(R.color.Black0);
img_night.setBackgroundResource(R.drawable.sun_icon);
img_main.setBackgroundResource(R.drawable.main2);
}else {
lin_main.setBackgroundResource(0);
img_night.setBackgroundResource(R.drawable.moon_icon);
img_main.setBackgroundResource(R.drawable.main);
}
if (!music){
stopService(new Intent(MainActivity.this,PlayMusic.class));
img_music.setBackgroundResource(R.drawable.music_off_icon);
}else {
startService(new Intent(MainActivity.this,PlayMusic.class));
img_music.setBackgroundResource(R.drawable.music_on_icon);
}
}
public void set_night(View view){
YoYo.with(Techniques.RotateIn).duration(800).playOn(img_night);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (night_mode){
lin_main.setBackgroundResource(0);
img_night.setBackgroundResource(R.drawable.moon_icon);
img_main.setBackgroundResource(R.drawable.main);
sharedP.edit().putBoolean(Items.NIGHT_MODE, false).apply();
night_mode=false;
}else {
lin_main.setBackgroundResource(R.color.Black0);
img_night.setBackgroundResource(R.drawable.sun_icon);
img_main.setBackgroundResource(R.drawable.main2);
sharedP.edit().putBoolean(Items.NIGHT_MODE, true).apply();
night_mode=true;
}
}
},800);
}
#Override
protected void onResume() {
super.onResume();
get_night();
}
#Override
protected void onDestroy() {
stopService(new Intent(MainActivity.this,PlayMusic.class));
super.onDestroy();
}
public void finish(View view) {
mDrawer.closeMenu(true);
finish();
}
#SuppressLint("ResourceAsColor")
private void taptarget(){
new MaterialTapTargetPrompt.Builder(MainActivity.this)
.setTarget(R.id.img_night)
.setPrimaryText("فعال کردن حالت شب")
.setSecondaryText("با زدن این دکمه میتوانید حالت مطالعه در شب را فعال یا غیر فعال کنید")
//.setPrimaryTextColour(Color.parseColor("#13dc74"))
// .setSecondaryTextColour(Color.parseColor("#13dc74"))
.setFocalColour(R.color.mycolorGray)
.setBackButtonDismissEnabled(false)
.setBackgroundColour(Color.parseColor("#635B5B"))
.setPromptStateChangeListener(new MaterialTapTargetPrompt.PromptStateChangeListener()
{
#Override
public void onPromptStateChanged(MaterialTapTargetPrompt prompt, int state)
{
if (state == MaterialTapTargetPrompt.STATE_FOCAL_PRESSED|| state==MaterialTapTargetPrompt.STATE_NON_FOCAL_PRESSED)
{
// User has pressed the prompt target
//Toast.makeText(MainActivity.this, "اولی", Toast.LENGTH_SHORT).show();
txt_target();
}
}
})
.show();
}
private void txt_target(){
new MaterialTapTargetPrompt.Builder(MainActivity.this)
.setTarget(R.id.img_icon)
.setFocalColour(R.color.mycolorGray)
.setPrimaryText("منوی کشویی")
.setSecondaryText("با زدن این دکمه منوی کشویی برنامه باز خواهد شد که شامل آیتم های مختلفی می باشد")
.setBackgroundColour(Color.parseColor("#635B5B"))
.setPromptStateChangeListener(new MaterialTapTargetPrompt.PromptStateChangeListener()
{
#Override
public void onPromptStateChanged(MaterialTapTargetPrompt prompt, int state)
{
if (state == MaterialTapTargetPrompt.STATE_FOCAL_PRESSED || state==MaterialTapTargetPrompt.STATE_NON_FOCAL_PRESSED)
{
// User has pressed the prompt target
//Toast.makeText(MainActivity.this, "دومی", Toast.LENGTH_SHORT).show();
target3();
}
}
})
.show();
}
private void target3(){
new MaterialTapTargetPrompt.Builder(MainActivity.this)
.setTarget(R.id.img_music)
.setPrimaryText("فعال/غیرفعال موزیک")
.setSecondaryText("با زدن این دکمه میتوانید موزیک پس زمینه حین مطالعه را پخش یا قطع کنید")
.setBackgroundColour(Color.parseColor("#635B5B"))
.setPromptStateChangeListener(new MaterialTapTargetPrompt.PromptStateChangeListener()
{
#Override
public void onPromptStateChanged(MaterialTapTargetPrompt prompt, int state)
{
if (state == MaterialTapTargetPrompt.STATE_FOCAL_PRESSED || state==MaterialTapTargetPrompt.STATE_NON_FOCAL_PRESSED)
{
// User has pressed the prompt target
//Toast.makeText(MainActivity.this, "دومی", Toast.LENGTH_SHORT).show();
target4();
}
}
})
.show();
}
private void target4(){
new MaterialTapTargetPrompt.Builder(MainActivity.this)
.setTarget(R.id.img_setting)
.setPrimaryText("تنظیمات")
.setSecondaryText("با زدن این دکمه بخش تنظیمات باز خواهد شد که شامل تغییر فونت متن ، سایز متن و ... می باشد")
.setBackgroundColour(Color.parseColor("#635B5B"))
.setPromptStateChangeListener(new MaterialTapTargetPrompt.PromptStateChangeListener()
{
#Override
public void onPromptStateChanged(MaterialTapTargetPrompt prompt, int state)
{
if (state == MaterialTapTargetPrompt.STATE_FOCAL_PRESSED || state==MaterialTapTargetPrompt.STATE_NON_FOCAL_PRESSED)
{
// User has pressed the prompt target
//Toast.makeText(MainActivity.this, "دومی", Toast.LENGTH_SHORT).show();
sharedP.edit().putBoolean(Items.INTROPAGE, false).apply();
}
}
})
.show();
}
#Override
public void onBackPressed() {
if (!(exit ==null)){
super.onBackPressed();
//MainActivity.this.finish();
}else {
exit = Toast.makeText(this,"برای خروج دوباره بزنید",Toast.LENGTH_LONG);
exit.show();
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
exit= null;
}
},3000);
}
}
this my main activity xml code:
Splash Screen Activity Run enters Intro Page. After clicking the reject or complete button, the program will not enter the activity menu and the program will close.
Please follow the below options. Hope your problem will be solved.
1) Your Manifest Must Change like this Activity name must Specified like ".YourActivityname"
<activity
android:name=".MainActivity" >
</activity>
2) Clean and rebuilt the project and Hope it will work.
You forgot find view btn_last_story add it to onCreate
btn_last_story = findViewById(R.id.btn_last_story);

Android Java app fails to send selected file/data via Bluetooth

My current android app can turn on Bluetooth, make itself discoverable, list paired devices, and select a file from the device ( ie an image). However when I attempted to hit "send" the app seems to crash with an error. Not sure if it's refusing to send, or if it's not actually obtaining the file (yesterday I had a problem where it refused to send the selected, saying for me to select a file repeatedly. I will post the crash results and my mainActivity code. If anyone suggestions or ideas, please let me know.
Error: Debugging device
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.bluetooth_demoproject, PID: 17593
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=300, data=null} to activity {com.example.bluetooth_demoproject/com.example.bluetooth_demoproject.MainActivity}: android.os.FileUriExposedException: file:///storage/emulated/0/Pictures/Screenshots/Screenshot_20161013-215137.png exposed beyond app through ClipData.Item.getUri()
at android.app.ActivityThread.deliverResults(ActivityThread.java:4107)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4150)
at android.app.ActivityThread.-wrap20(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1517)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6120)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: android.os.FileUriExposedException: file:///storage/emulated/0/Pictures/Screenshots/Screenshot_20161013-215137.png exposed beyond app through ClipData.Item.getUri()
at android.os.StrictMode.onFileUriExposed(StrictMode.java:1799)
at android.net.Uri.checkFileUriExposed(Uri.java:2346)
at android.content.ClipData.prepareToLeaveProcess(ClipData.java:832)
at android.content.Intent.prepareToLeaveProcess(Intent.java:8909)
at android.content.Intent.prepareToLeaveProcess(Intent.java:8894)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1517)
at android.app.Activity.startActivityForResult(Activity.java:4224)
at android.app.Activity.startActivityForResult(Activity.java:4183)
at android.app.Activity.startActivity(Activity.java:4507)
at android.app.Activity.startActivity(Activity.java:4475)
at com.example.bluetooth_demoproject.MainActivity.onActivityResult(MainActivity.java:350)
at android.app.Activity.dispatchActivityResult(Activity.java:6917)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4103)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4150) 
at android.app.ActivityThread.-wrap20(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1517) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6120) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
Disconnected from the target VM, address: 'localhost:8601', transport: 'socket'
Here is my MainActivity
package com.example.bluetooth_demoproject;
import android.app.Activity;
import android.app.Dialog;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.bluetooth.BluetoothA2dp;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Set;
import java.io.File;
import java.util.List;
import java.util.ArrayList;
public class MainActivity extends Activity {
// Creating objects -----------------------------
private static final int REQUEST_ENABLE_BT = 0;
private static final int REQUEST_BLU = 1;
// private static final int REQUEST_DISCOVER_BT_ = 1;
private static int CUSTOM_DIALOG_ID = 0;
ListView dialog_ListView;
TextView mBluetoothStatus, mPairedDevicesList, mTextFolder;
ImageView mBluetoothIcon;
Button mOnButton, mDiscoverableButton, mPairedDevices, mbuttonOpenDialog, msendBluetooth, mbuttonUp;
File root, fileroot, curFolder;
EditText dataPath;
private static final int DISCOVER_DURATION = 300;
private List<String> fileList = new ArrayList<String>();
// -------------------------------------------------------
BluetoothAdapter mBlueAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataPath =(EditText)findViewById(R.id.FilePath);
mTextFolder = findViewById(R.id.folder);
mBluetoothStatus = findViewById(R.id.BluetoothStatus);
mBluetoothIcon = findViewById(R.id.bluetoothIcon);
mOnButton = findViewById(R.id.onButton);
// mOffButton = findViewById(R.id.offButton);
mDiscoverableButton = findViewById(R.id.discoverableButton);
mPairedDevices = findViewById(R.id.pairedDevices);
mPairedDevicesList = findViewById(R.id.pairedDeviceList);
mbuttonOpenDialog = findViewById(R.id.opendailog);
msendBluetooth = findViewById(R.id.sendBluetooth);
mbuttonUp = findViewById(R.id.up);
mbuttonOpenDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dataPath.setText("");
showDialog(CUSTOM_DIALOG_ID);
}
});
root = new
File(Environment.getExternalStorageDirectory().getAbsolutePath());
curFolder = root;
msendBluetooth.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
sendViaBluetooth();
}
});
//adapter
mBlueAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBlueAdapter == null){
mBluetoothStatus.setText("Bluetooth is not available");
return;
}
else {
mBluetoothStatus.setText("Bluetooth is available");
}
//if Bluetooth isnt enabled, enable it
if (!mBlueAdapter.isEnabled()) {
Intent enableBtIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
//set image according to bluetooth Status
if (mBlueAdapter.isEnabled()) {
mBluetoothIcon.setImageResource(R.drawable.action_on);
}
else {
mBluetoothIcon.setImageResource(R.drawable.action_off);
}
//on button Click
mOnButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if (!mBlueAdapter.isEnabled()) {
showToast("Turning Bluetooth on...");
// intent to on bluetooth
Intent intent = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, REQUEST_ENABLE_BT);
}
else {
showToast("Bluetooth is already on");
}
}
});
//discover Bluetooth button
mDiscoverableButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (!mBlueAdapter.isDiscovering()) {
showToast("Making device discoverable");
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(intent, REQUEST_BLU);
}
}
});
// off button click
// mOffButton.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// if (mBlueAdapter.isEnabled()) {
// showToast("Turning Bluetooth off...");
// // intent to turn off bluetooth
// mBluetoothIcon.setImageResource(R.drawable.action_off);
// }
// else{
// showToast("Bluetooth is already off");
// }
//
// }
//});
//get paired device button click
mPairedDevices.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mBlueAdapter.isEnabled()) {
mPairedDevices.setText("Paired Devices");
Set<BluetoothDevice> devices = mBlueAdapter.getBondedDevices();
for (BluetoothDevice device : devices){
mPairedDevices.append("\nDevice: " + device.getName() + "," + device );
}
}
else {
//bluetooth is off and cant get paired devices
showToast("Turn on bluetooth to get paired devices");
}
}
});
}
// #Override
// protected void onPrepareDialog(int id, Dialog dialog) {
// super.onPrepareDialog(id, dialog);
// switch (id) {
// case CUSTOM_DIALOG_ID:
// ListDir(curFolder);
// break;
// }
// }
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
if (id == CUSTOM_DIALOG_ID) {
dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.dailoglayout);
dialog.setTitle("Select Files");
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);
mTextFolder = (TextView) dialog.findViewById(R.id.folder);
mbuttonUp = (Button) dialog.findViewById(R.id.up);
mbuttonUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ListDir(curFolder.getParentFile());
}
});
dialog_ListView = (ListView) dialog.findViewById(R.id.dialoglist);
dialog_ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
File selected = new File(fileList.get(position));
if (selected.isDirectory()) {
ListDir(selected);
}
else if (selected.isFile()) {
getSelectedFile(selected);
}
else {
dismissDialog(CUSTOM_DIALOG_ID);
}
}
});
}
return dialog;
}
#Override
protected void onPrepareDialog(int id, Dialog dialog) {
super.onPrepareDialog(id, dialog);
if (id == CUSTOM_DIALOG_ID) {
ListDir(curFolder);
}
}
public void getSelectedFile(File f) {
dataPath.setText(f.getAbsolutePath());
fileList.clear();
dismissDialog(CUSTOM_DIALOG_ID);
}
public void ListDir(File f) {
if (f.equals(root)) {
mbuttonUp.setEnabled(false);
}
else {
mbuttonUp.setEnabled(true);
}
curFolder = f;
mTextFolder.setText(f.getAbsolutePath());
dataPath.setText(f.getAbsolutePath());
File[] files = f.listFiles();
fileList.clear();
for (File file : files) {
fileList.add(file.getPath());
}
ArrayAdapter<String> directoryList = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, fileList);
dialog_ListView.setAdapter(directoryList);
}
// exits to app --------------------------------
public void exit(View V) {
mBlueAdapter.disable();
Toast.makeText(this, "*** Now bluetooth is off...", Toast.LENGTH_LONG).show();
finish();
}
// send file via bluetooth ------------------------
public void sendViaBluetooth() {
if(!dataPath.equals(null)) {
if(mBlueAdapter == null) {
Toast.makeText(this, "Device doesnt support bluetooth", Toast.LENGTH_LONG).show();
}
else {
enableBluetooth();
}
}
else {
Toast.makeText(this, "please select a file", Toast.LENGTH_LONG).show();
}
}
public void enableBluetooth() {
showToast("Making device discoverable");
Intent discoveryIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoveryIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, DISCOVER_DURATION);
startActivityForResult(discoveryIntent, REQUEST_BLU);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == DISCOVER_DURATION && requestCode == REQUEST_BLU) {
Intent i = new Intent();
i.setAction(Intent.ACTION_SEND);// STOPPED HERE-----------------------------------------------------------------
i.setType("*/*");
File file = new File(dataPath.getText().toString());
i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
PackageManager pm = getPackageManager();
List<ResolveInfo> list = pm.queryIntentActivities(i, 0);
if (list.size() > 0) {
String packageName = null;
String className = null;
boolean found = false;
for (ResolveInfo info : list) {
packageName = info.activityInfo.packageName;
if (packageName.equals("com.android.bluetooth")) {
className = info.activityInfo.name;
found = true;
break;
}
}
//CHECK BLUETOOTH available or not------------------------------------------------
if (!found) {
Toast.makeText(this, "Bluetooth not been found", Toast.LENGTH_LONG).show();
} else {
i.setClassName(packageName, className);
startActivity(i);
}
}
} else {
Toast.makeText(this, "Bluetooth is cancelled", Toast.LENGTH_LONG).show();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
// if (id == R.id.action_settings) {
// Toast.makeText(this, "**********************************\nDeveloper: www.santoshkumarsingh.com\n**********************************", Toast.LENGTH_LONG).show();
// return true;
// }
return super.onOptionsItemSelected(item);
}
//toast message function
private void showToast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT) .show();
}
}
You have trouble with file exchange not with BLE.
Did you ever read Android FileUriExposedException?

Error when I push MySQL data with onPostExecute

I'm new at programming. I'm doing a login system, but when I log in, I get that error. I don’t know how to solve it. And I have one more question: Is making a login system with chat and friends (add, Remove) system too hard?
Because I want to do that, but I just started programming one week ago, can I do this?
FATAL EXCEPTION: main
Process: complete.lyne.myapplication, PID: 18933
java.lang.ArrayIndexOutOfBoundsException: length=2; index=2
at complete.lyne.myapplication.Login$SolicitaDados.onPostExecute(Login.java:110)
at complete.lyne.myapplication.Login$SolicitaDados.onPostExecute(Login.java:91)
at android.os.AsyncTask.finish(AsyncTask.java:660)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:677)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Here is my code:
package complete.lyne.myapplication;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
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.TextView;
import android.widget.Toast;
import java.io.IOException;
// import br.com.simplepass.loading_button_lib.customViews.CircularProgressButton;
public class Login extends AppCompatActivity {
EditText loginEmail, loginSenha;
Button btLogar;
TextView refCadastrar;
String url = "";
String parametro = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
loginEmail = (EditText)findViewById(R.id.loginEmail);
loginSenha = (EditText)findViewById(R.id.loginSenha);
btLogar = (Button)findViewById(R.id.btLogar);
refCadastrar = (TextView)findViewById(R.id.refCadastrar);
refCadastrar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent abreCadastro = new Intent(Login.this, Cadastro.class);
startActivity(abreCadastro);
}
});
btLogar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ConnectivityManager connectivityManager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
String email = loginEmail.getText().toString();
String senha = loginSenha.getText().toString();
if(email.isEmpty() && senha.matches(".*[a-z].*")) {
loginEmail.setError("Insira seu endereço de Email.");
} else if (email.matches(".*[a-z].*") && senha.isEmpty()) {
loginSenha.setError("Insira sua Senha.");
} else if (email.isEmpty() && senha.isEmpty()) {
Toast.makeText(getApplicationContext(), "Nenhum campo pode ficar vazio.", Toast.LENGTH_LONG).show();
} else {
// Casa
url = "http://192.168.1.100/lyne/logar.php";
// Badran
// url = "http://172.16.2.15/lyne/logar.php";
parametro = "email=" + email + "&senha=" + senha;
new SolicitaDados().execute(url);
}
}
else {
Toast.makeText(getApplicationContext(), "Nenhuma conexão com a Internet foi encontrada.", Toast.LENGTH_LONG).show();
}
}
});
}
private class SolicitaDados extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return Conexao.postDados(urls[0], parametro);
}
#Override
protected void onPostExecute(String resultado) {
if(resultado != null) {
if (resultado.contains("login_ok")) {
String[] dados = resultado.split(",");
Intent abreHome = new Intent(Login.this, Home.class);
abreHome.putExtra("idusu", dados[1]);
abreHome.putExtra("nomeusu", dados[2]);
startActivity(abreHome);
} else {
Toast.makeText(getApplicationContext(), "Usuário ou senha incorretos.", Toast.LENGTH_LONG).show();
}
}
}
}
#Override
protected void onPause() {
super.onPause();
finish();
}
}
You are asking for an index that doesn't exist inside of you array.
It seems like you're looking for two objects, not three, but you are looking in the wrong place.
You should edit your code to look like this:
abreHome.putExtra("idusu", dados[0]);
abreHome.putExtra("nomeusu", dados[1]);
You are splitting the string:
String[] dados = resultado.split(",");
And assuming there will be at least three pieces:
abreHome.putExtra("idusu", dados[1]);
abreHome.putExtra("nomeusu", dados[2]);
But looks like that's is not the case. Check for the length of dados before you go and access elements from it.

ImageButton to open a new activity

I am building an android app and on the main layout i have 3 Image Buttons which when clicked they must each open a new activity.
When I run the app and pressed on them the app crushes. this is the code i am using:
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageButton converterbtn = (ImageButton)findViewById(R.id.btnConvert);
ImageButton placesbtn = (ImageButton)findViewById(R.id.imagBtnPlace);
ImageButton weatherbtn = (ImageButton)findViewById(R.id.imgbtnweather);
//Open Weather Activity
if (weatherbtn.isPressed() == true) {
weatherbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(), weather_mainActivity.class);
startActivity(intent);
}
}); //Open Currency Activity
}else if (converterbtn.isPressed() == true) {
converterbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent1 = new Intent(getApplicationContext(), CurrencyConverter_MainActivity.class);
startActivity(intent1);
}
});//Open Places Activity
} else if (placesbtn.isPressed()) {
placesbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent1 = new Intent(getApplicationContext(), Places_mainActivity.class);
startActivity(intent1);
}
});
}
}
Manifest.xml
<activity android:name=".CurrencyConverter_MainActivity"/>
<activity android:name=".weather_mainActivity"/>
Any ideas why that happens? All the other posts ive checked are doing it with this way but on mine it doesnt seem to work.
Android Monitor log
01-08 03:00:58.288 22447-22447/? D/AndroidRuntime: Shutting down VM
--------- beginning of crash
01-08 03:01:01.127 1236-1547/? D/AudioFlinger: mixer(0xf4480000) throttle end: throttle time(56)
01-08 03:01:01.151 1550-21914/? D/OpenGLRenderer: endAllStagingAnimators on 0x7f0b1b83d400 (RippleDrawable) with handle 0x7f0b1b8bb540
01-08 03:01:01.192 1550-1954/? D/GraphicsStats: Buffer count: 3
Weather_MainActivity.java
package com.android.example.cwapp;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import butterknife.ButterKnife;
import butterknife.InjectView;
public class weather_mainActivity extends AppCompatActivity {
public static final String TAG = weather_mainActivity.class.getSimpleName();
private CurrentWeather mCurrentWeather;
LocationManager locationManager;
#InjectView(R.id.timeLabel) TextView mTimeLabel;
#InjectView(R.id.temperatureLabel)TextView mTemperatureLabel;
#InjectView(R.id.humidityValue)TextView mHumidityValue;
#InjectView(R.id.precipValue)TextView mPrecipValue;
#InjectView(R.id.summaryLabel)TextView mSummaryLabel;
#InjectView(R.id.iconImageView)ImageView mIconImageView;
#InjectView(R.id.refreshImageView)ImageView mRefreshImageView;
#InjectView(R.id.progressBar)ProgressBar mProgressBar;
#InjectView(R.id.locationLabel)TextView mLocation;
public double latitude /*= 34.7720*/;
public double longitude /*= 32.4297*/;
//Location Manager
private boolean checkLocation() {
if (!isLocationEnabled())
showAlert();
return isLocationEnabled();
}
private void showAlert() {
final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Enable Location")
.setMessage("Your Locations Settings is set to 'Off'.\nPlease Enable Location to " +
"use this app")
.setPositiveButton("Location Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
}
});
dialog.show();
}
private boolean isLocationEnabled() {
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
private final LocationListener locationListenerBest = new LocationListener() {
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
mProgressBar.setVisibility(View.INVISIBLE);
mRefreshImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getForecast(latitude, longitude);
}
});
getForecast(latitude, longitude);
Log.d(TAG, "Main UI code is running!");
}
private void getForecast(double latitude, double longitude) {
String apiKey = "6180f6e1b6747c1da3cb4638ea9d2961";
String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
"/" + latitude + "," + longitude;
if (isNetworkAvailable()) {
toggleRefresh();
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(forecastUrl)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleRefresh();
}
});
alertUserAboutError();
}
#Override
public void onResponse(Response response) throws IOException {
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleRefresh();
}
});
try {
String jsonData = response.body().string();
Log.v(TAG, jsonData);
if (response.isSuccessful()) {
mCurrentWeather = getCurrentDetails(jsonData);
runOnUiThread(new Runnable() {
#Override
public void run() {
updateDisplay();
}
});
} else {
alertUserAboutError();
}
} catch (IOException e) {
Log.e(TAG, "Exception caught: ", e);
} catch (JSONException e) {
Log.e(TAG, "Exception caught: ", e);
}
}
});
} else {
Toast.makeText(this, getString(R.string.network_unavailable_message),
Toast.LENGTH_LONG).show();
}
}
private void toggleRefresh() {
if (mProgressBar.getVisibility() == View.INVISIBLE) {
mProgressBar.setVisibility(View.VISIBLE);
mRefreshImageView.setVisibility(View.INVISIBLE);
} else {
mProgressBar.setVisibility(View.INVISIBLE);
mRefreshImageView.setVisibility(View.VISIBLE);
}
}
private void updateDisplay() {
float temp = mCurrentWeather.getTemperature();
String temp2 = Float.toString((temp - 32) * (5 / 9));
mTemperatureLabel.setText(temp2 + "");
mTimeLabel.setText("At " + mCurrentWeather.getFormattedTime() + " it will be");
mHumidityValue.setText(mCurrentWeather.getHumidity() + "");
mPrecipValue.setText(mCurrentWeather.getPrecipChance() + "%");
mSummaryLabel.setText(mCurrentWeather.getSummary());
mLocation.setText(mCurrentWeather.getTimeZone());
Drawable drawable = getResources().getDrawable(mCurrentWeather.getIconId());
mIconImageView.setImageDrawable(drawable);
}
private CurrentWeather getCurrentDetails(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
Log.i(TAG, "From JSON: " + timezone);
JSONObject currently = forecast.getJSONObject("currently");
CurrentWeather currentWeather = new CurrentWeather();
currentWeather.setHumidity(currently.getDouble("humidity"));
currentWeather.setTime(currently.getLong("time"));
currentWeather.setIcon(currently.getString("icon"));
currentWeather.setPrecipChance(currently.getDouble("precipProbability"));
currentWeather.setSummary(currently.getString("summary"));
currentWeather.setTemperature(currently.getDouble("temperature"));
currentWeather.setTimeZone(timezone);
Log.d(TAG, currentWeather.getFormattedTime());
return currentWeather;
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
private void alertUserAboutError() {
AlertDialogFragment_weather dialog = new AlertDialogFragment_weather();
dialog.show(getFragmentManager(), "error_dialog");
}
};
RUN Log
01-09 21:29:30.827 5610-5610/? E/memtrack: Couldn't load memtrack module (No such file or directory)
01-09 21:29:30.827 5610-5610/? E/android.os.Debug: failed to load memtrack module: -2
01-09 21:29:30.864 5610-5627/? E/art: Thread attaching while runtime is shutting down: Binder_2
01-09 21:29:30.869 5614-5614/? E/memtrack: Couldn't load memtrack module (No such file or directory)
01-09 21:29:30.870 5614-5614/? E/android.os.Debug: failed to load memtrack module: -2
01-09 21:29:30.916 1548-1596/? E/InputDispatcher: channel '6ba3a14 com.android.example.cwapp/com.android.example.cwapp.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
01-09 21:29:31.830 5633-5633/? E/memtrack: Couldn't load memtrack module (No such file or directory)
01-09 21:29:31.830 5633-5633/? E/android.os.Debug: failed to load memtrack module: -2
01-09 21:29:32.033 1195-1309/? E/SurfaceFlinger: ro.sf.lcd_density must be defined as a build property
01-09 21:29:33.170 1921-2145/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0xedc344f0
01-09 21:30:01.551 5641-5654/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f44b819a240
01-09 21:30:02.902 5641-5654/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f44b1cf8310
01-09 21:30:04.739 5641-5654/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f44b819b580
01-09 21:30:06.655 5641-5654/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f44b1cf8380
01-09 21:30:08.253 5641-5654/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f44b1bed700
01-09 21:30:09.115 5641-5641/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.android.example.cwapp, PID: 5641
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.android.example.cwapp/com.android.example.cwapp.Places_mainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at com.android.example.cwapp.Places_mainActivity.onCreate(Places_mainActivity.java:36)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
01-09 21:30:11.307 1548-1601/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f44b1c8f020
01-09 21:30:11.326 1548-1937/? E/JavaBinder: !!! FAILED BINDER TRANSACTION !!! (parcel size = 104)
Add CurrentWeather.class activity in your mainfest like this
<activity android:name=".CurrencyConverter_MainActivity"/>
<activity android:name=".weather_mainActivity"/>
<activity android:name=".CurrentWeather"/>
You should display your stack trace, but you don't need View.OnClickListner, not sure if that's causing it, but just have weatherbtn.setOnClickListener(new OnClickListener() {...
Other than that, there isn't anything wrong with how you're calling your activity.

android error "cant create handler inside thread that has not called looper.prepare" [duplicate]

This question already has answers here:
Can't create handler inside thread that has not called Looper.prepare()
(30 answers)
Closed 8 years ago.
I have a dialog fragment named ShareId and a service named
SendMapDataService.When i called the SendMapDataService from ShareId
got error cant create handler inside thread that has not called
looper.prepare....
ShareId
package dialog;
import com.rosaloves.bitlyj.Url;
import static com.rosaloves.bitlyj.Bitly.*;
import java.util.Calendar;
import updatedata.GPSTracker;
import updatedata.SendMapDataService;
import com.example.map.LocationSendActivity;
import com.example.map.R;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class ShareId extends DialogFragment {
Button ok,cancel;
public static EditText et;
private double latt,lngt;
public static String sid,lat,lng,time;
ProgressDialog pDialog;
GPSTracker gps;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View V = inflater.inflate(R.layout.shareid, container, false);
ok=(Button)V.findViewById(R.id.button1);
cancel=(Button)V.findViewById(R.id.button2);
et=(EditText)V.findViewById(R.id.editText1);
getDialog().setTitle("Enter Share_id");
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
sid=et.getText().toString();
if(sid.length() == 0 ){
Toast.makeText(getActivity(),"Please enter share_id",Toast.LENGTH_SHORT).show();
}else{
new ShareTask().execute();
}
}
});
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
getDialog().dismiss();
}
});
return V;
}
class ShareTask extends AsyncTask<String, String, String>{
StringBuffer sbf2=new StringBuffer();
boolean b=false;
int ch;
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading Application. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
// Create download Url
Url url = as("adeveloper962", "R_38e071119c3048db892f3aca82b03392")
.call(shorten("http://map.rhaasoft.net//locationfile/download.php"));
String ul = url.getShortUrl();
sbf2.append("Click for download LocationMapping file"+" "+ul+"\n");
//Create location Url
gps = new GPSTracker(getActivity());
if(gps.canGetLocation()){
Log.e("Shareid", "hello");
b=true;
//get Time
time= java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
//get latitude longitude
latt = gps.getLatitude();
lat=String.valueOf(latt);
lngt= gps.getLongitude();
lng=String.valueOf(lngt);
//add link
Uri.Builder ur=Uri.parse("http://myapp.com/?").buildUpon();
ur.appendQueryParameter("la", lat);
ur.appendQueryParameter("ln", lng);
ur.appendQueryParameter("ti", time);
ur.appendQueryParameter("id", sid);
ur.build();
//shorting url
Url url1 = as("adeveloper962", "R_38e071119c3048db892f3aca82b03392")
.call(shorten(ur.toString()));
String ul1 = url1.getShortUrl();
//append
sbf2.append("Click for show location"+" "+ul1);
}else{
b=false;
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
getActivity().runOnUiThread(new Runnable() {
public void run() {
if(b == true){
getDialog().dismiss();
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "Location Shareing");
intent.putExtra(Intent.EXTRA_TEXT, sbf2.toString());
startActivity(Intent.createChooser(intent, "Select Application for share"));
//Send continue data
ch=LocationSendActivity.state;
if(ch == 0 || ch ==1){
LocationSendActivity.i=1;
LocationSendActivity.u_id=sid;
getActivity().startService(new Intent(getActivity(),SendMapDataService.class));
}else{
LocationSendActivity.i=0;
getActivity().stopService(new Intent(getActivity(),SendMapDataService.class));
}
}else{
getDialog().dismiss();
gps.showSettingsAlert();
}
}
});
}
}
}
SendMapDataService..
package updatedata;
import java.util.Calendar;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.map.FunctionCall;
import com.example.map.LocationSendActivity;
import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
public class SendMapDataService extends Service {
private Handler handler;
private String id1,lat1,lng1,time1;
private double lat,lng;
GPSTracker gps;
private long total,val,min;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
gps=new GPSTracker(getApplicationContext());
return null;
}
public int onStartCommand(Intent intent, int flags, int startId) {
id1=LocationSendActivity.u_id;
// Log.e("Myid", String.valueOf(LocationSendActivity.u_id));
// get time from time interval
if(min == 1){
val=15;
}else if(min == 2){
val=30;
}else if(min == 3){
val=60;
}else if(min == 4){
val=5*60;
}else if(min == 5){
val=10*60;
}
else{
val=15;
}
total=(long) (val*1000);
// Log.e("Seconds", String.valueOf(total));
// Start handler
handler=new Handler();
handler.postDelayed(runn, 1000);
// Looper.loop();
return START_STICKY;
}
Runnable runn = new Runnable() {
#Override
public void run() {
gps=new GPSTracker(getApplicationContext());
if(gps.canGetLocation()){
lat = gps.getLatitude();
lng = gps.getLongitude();
time1=java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
lat1=String.valueOf(lat);
lng1=String.valueOf(lng);
new SendUpdatedData(id1,lat1,lng1,time1).execute();
handler.postDelayed(this, total);
}else{
gps.showSettingsAlert();
}
}
};
public void onDestroy() {
super.onDestroy();
handler.removeCallbacks(runn,null);
Toast.makeText(this, "Data Send Service Destroyed", Toast.LENGTH_LONG).show();
}
class SendUpdatedData extends AsyncTask<String, String, String>{
String id2,lat2,lng2,time2;
int success,val,update;
public SendUpdatedData(String id, String lat,String lng,String time) {
// TODO Auto-generated constructor stub
this.id2=id;
this.lat2=lat;
this.lng2=lng;
this.time2=time;
}
protected void onPreExecute(){
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
FunctionCall fc=new FunctionCall();
JSONObject jo=fc.sendUpdateData(id2,lat2,lng2,time2);
try{
success=jo.getInt("success");
update=jo.getInt("update");
}catch(JSONException e){
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url){
if (success==1){
if(update == 1){
Toast.makeText(getApplication(),"Data Updated", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplication(),"New Data Inserted", Toast.LENGTH_SHORT).show();
}
}
else{
Toast.makeText(getApplication(),"Data Not Send", Toast.LENGTH_SHORT).show();
}
}
}
}
LogCat....
02-06 12:16:43.740: W/System.err(15622): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
02-06 12:16:43.740: W/System.err(15622): at android.os.Handler.<init>(Handler.java:121)
02-06 12:16:43.740: W/System.err(15622): at android.location.LocationManager$ListenerTransport$1.<init>(LocationManager.java:137)
02-06 12:16:43.750: W/System.err(15622): at android.location.LocationManager$ListenerTransport.<init>(LocationManager.java:137)
02-06 12:16:43.750: W/System.err(15622): at android.location.LocationManager._requestLocationUpdates(LocationManager.java:708)
02-06 12:16:43.750: W/System.err(15622): at android.location.LocationManager.requestLocationUpdates(LocationManager.java:630)
02-06 12:16:43.750: W/System.err(15622): at updatedata.GPSTracker.getLocation(GPSTracker.java:65)
02-06 12:16:43.750: W/System.err(15622): at updatedata.GPSTracker.<init>(GPSTracker.java:44)
02-06 12:16:43.750: W/System.err(15622): at dialog.ShareId$ShareTask.doInBackground(ShareId.java:96)
02-06 12:16:43.750: W/System.err(15622): at dialog.ShareId$ShareTask.doInBackground(ShareId.java:1)
02-06 12:16:43.750: W/System.err(15622): at android.os.AsyncTask$2.call(AsyncTask.java:185)
02-06 12:16:43.750: W/System.err(15622): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
02-06 12:16:43.750: W/System.err(15622): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
02-06 12:16:43.750: W/System.err(15622): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
02-06 12:16:43.750: W/System.err(15622): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
02-06 12:16:43.750: W/System.err(15622): at java.lang.Thread.run(Thread.java:1096)
Just call Looper.prepare(); above the line where you got exception..

Categories