Android Application and Observable - android

i'm developing a simple application on android studio. I'm using "application", "observable", and many more. i got some error like this:
java.lang.RuntimeException: Unable to start activity ComponentInfo{id.wdharmana.doahindu/id.wdharmana.doahindu.MainActivity}: java.lang.ClassCastException: android.app.Application cannot be cast to id.wdharmana.doahindu.app.DoaApplication
2nd error
Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to id.wdharmana.doahindu.app.DoaApplication
3rd error
at id.wdharmana.doahindu.MainActivity.onCreate(MainActivity.java:52)
This is my full MainActivity.java:
package id.wdharmana.doahindu;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import id.wdharmana.doahindu.adapter.ListJudulAdapter;
import id.wdharmana.doahindu.app.DoaApplication;
import id.wdharmana.doahindu.data.DefaultData;
import id.wdharmana.doahindu.helper.DoaHelper;
import id.wdharmana.doahindu.model.DoaModel;
import id.wdharmana.doahindu.model.DoaObserver;
import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;
public class MainActivity extends AppCompatActivity implements Observer {
private ListView lvJudul;
private ArrayList<DoaModel> listJudul;
private DoaHelper doaHelper;
public ListJudulAdapter listJudulAdapter;
private DoaApplication application;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvJudul = (ListView)findViewById(R.id.lvListJudul);
listJudul = new ArrayList<DoaModel>();
application = (DoaApplication) getApplication();
application.getDoaObserver().addObserver(this);
doaHelper = new DoaHelper(MainActivity.this);
doaHelper.open();
listJudul = doaHelper.getAllData();
if (listJudul.size()>0) {
bindData();
}else{
insertDefaultData();
}
lvJudul.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
showMeaningDialog(MainActivity.this, listJudul.get(arg2));
}
});
lvJudul.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
deleteDialog(listJudul.get(arg2).getId());
return false;
}
});
}
private void insertDefaultData() {
// TODO Auto-generated method stub
new StoreDefaultData().execute();
}
public void update(Observable observable, Object o) {
if (o.equals(DoaObserver.NEED_TO_REFRESH)){
bindData();
}
}
private class StoreDefaultData extends AsyncTask<Void, Void, Void>{
ProgressDialog mProgressDialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setTitle(getString(R.string.notify_input_data));
mProgressDialog.setMessage(getString(R.string.text_please_wait));
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
for (int i = 0; i < DefaultData.defaultData.length; i++) {
doaHelper.insert(DoaModel.getDoaModel(DefaultData.defaultData[i][0],
DefaultData.defaultData[i][1]));
}
listJudul = doaHelper.getAllData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
mProgressDialog.dismiss();
listJudulAdapter = new ListJudulAdapter(MainActivity.this, listJudul);
lvJudul.setAdapter(listJudulAdapter);
}
}
#Override
protected void onDestroy() {
if (doaHelper != null){
doaHelper.close();
}
super.onDestroy();
}
public static void showMeaningDialog(final Activity activity, final DoaModel item) {
final Dialog dialog = new Dialog(activity, R.style.AppCompatAlertDialogStyle);
dialog.setContentView(R.layout.dialog_konten);
dialog.setCancelable(true);
TextView txtKonten = (TextView)dialog.findViewById(R.id.txtMeaning);
TextView txtJudul = (TextView)dialog.findViewById(R.id.txtWord);
Button btnTutup = (Button)dialog.findViewById(R.id.btnTutup);
Button btnEdit = (Button)dialog.findViewById(R.id.btnEdit);
txtKonten.setText(item.getKonten());
txtJudul.setText(item.getJudul());
btnEdit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
//FormInputUpdateActivity.toFormInputUpdate(activity, item);
dialog.dismiss();
}
});
btnTutup.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
dialog.show();
}
private void deleteDialog(final int id) {
// TODO Auto-generated method stub
final Dialog dialog = new Dialog(MainActivity.this, R.style.AppCompatAlertDialogStyle);
dialog.setTitle("Hapus");
//dialog.setContentView(R.layout.dialog_delete);
dialog.setCancelable(true);
// Button btnYes = (Button)dialog.findViewById(R.id.btnDeleteYes);
// Button btnCancel = (Button)dialog.findViewById(R.id.btnDeleteCancel);
// btnYes.setOnClickListener(new OnClickListener() {
// public void onClick(View v) {
// // TODO Auto-generated method stub
// doaHelper.delete(id);
// dialog.dismiss();
// Toast.makeText(MainActivity.this, getString(R.string.text_success_delete), Toast.LENGTH_LONG).show();
// application.getDoaObserver().refresh();
// }
// });
//btnCancel.setOnClickListener(new View.OnClickListener() {
// public void onClick(View arg0) {
// TODO Auto-generated method stub
// dialog.dismiss();
// }
//});
dialog.show();
}
public void bindData(){
if (listJudul.size()>0) {
listJudul.clear();
}
listJudul = doaHelper.getAllData();
listJudulAdapter = new ListJudulAdapter(MainActivity.this, listJudul);
lvJudul.setAdapter(listJudulAdapter);
listJudulAdapter.notifyDataSetChanged();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_activity_main, menu);
SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =
(SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName()));
return true;
}
}
This is DoaApplication.java
package id.wdharmana.doahindu.app;
import android.app.Application;
import id.wdharmana.doahindu.model.DoaObserver;
/**
* Created by WDHARMANA on 9/18/2015.
*/
public class DoaApplication extends Application {
DoaObserver doaObserver;
#Override
public void onCreate() {
super.onCreate();
doaObserver = new DoaObserver();
}
public DoaObserver getDoaObserver(){
return doaObserver;
}
}
No error when build. Please tell me if you have some suggestions. Thanks in advance.

Put DoaApplication in your manifest, in the <application> node as android:name="id.wdharmana.doahindu.app.DoaApplication"

Please make sure your AndroidManifest.xml like that:
<application
android:name="id.wdharmana.doahindu.app.DoaApplication"
... >
...
</application>
I think you forgot to add your

Related

Regarding validation of a paint drawn on a canvas in android

Sir, we are developing an app to teach small children write alphabets.. Here we show a screen with two images where one image is on the right side it is just to show the image of the alphabet, and the the other one is a light image where the user can draw on image for practise. I want to validate the image drawn by the user whether he has drawn correctly on the base image or not.!
(Note: I exactly dont know what is the use of "Scaling" which i used in it.)Can i please get a solution because i tried a lot but cudnt get an answer
The code is:
enter code here
package com.example.androidhive;
import com.example.androidhive.ColorPickerDialog.OnColorSelectedListener;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.Bundle;
import android.support.v4.view.MotionEventCompat;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.Toast;
import android.widget.ViewFlipper;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class FullImgTwoActivity extends Activity implements OnTouchListener {
int pp;
int pickupLinesItemIndex;
int position;
PaintView paintView;
ViewFlipper layout;
int size = 0;
int progress = 0;
ImageView imageView1;
private Bitmap bmp;
private Bitmap operation;
GetScaling scaling;
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.full_image);
paintView = new PaintView(this);
scaling=new GetScaling(this);
layout = (ViewFlipper) findViewById(R.id.view1);
Intent i = getIntent();
position = i.getExtras().getInt("id");
final ImageAdapterTwo imageAdapterTwo = new ImageAdapterTwo(this);
imageView1 = (ImageView) findViewById(R.id.imageView1);
imageView1.setImageResource(imageAdapterTwo.mThumbIdsx[position]);
bmp=imageView1.getDrawingCache();
layout.setBackgroundResource(imageAdapterTwo.mThumbIdsy[position]);
paintView.setLayoutParams(new LinearLayout.LayoutParams(500, 500));
layout.addView(paintView);
ImageView back = (ImageView) findViewById(R.id.imageView3);
back.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (pickupLinesItemIndex < imageAdapterTwo.mThumbIdsw.length) {
if (position <= 0) {
Toast.makeText(getApplicationContext(), "This is the starting alphabet", 90)
.show();
} else {
imageView1
.setImageResource(imageAdapterTwo.mThumbIdsx[--position]);
layout
.setBackgroundResource(imageAdapterTwo.mThumbIdsy[position]);
}
}
}
});
ImageView nexta = (ImageView) findViewById(R.id.imageView4);
nexta.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (pickupLinesItemIndex > imageAdapterTwo.mThumbIdsw.length) {
//if (position <=imageAdapter.mThumbIds.length) {
Toast.makeText(getApplicationContext(), "This level is done", 90)
.show();
} else {
imageView1
.setImageResource(imageAdapterTwo.mThumbIdsx[++position]);
layout
.setBackgroundResource(imageAdapterTwo.mThumbIdsy[position]);
//}
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
getMenuInflater().inflate(R.menu.home, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.select_color_menu:
showColorPickerDialogDemo();
break;
case R.id.select_clear_menu:
paintView.clear();
paintView.invalidate();
break;
case R.id.pointers_select_menu:
// pointerDialog();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
private void pointerDialog() {
// TODO Auto-generated method stub
final Dialog d = new Dialog(FullImgTwoActivity.this);
d.setTitle("Increase pointer size");
d.setContentView(R.layout.pointerssize);
SeekBar bar = (SeekBar) d.findViewById(R.id.seekBar1);
Button save = (Button) d.findViewById(R.id.save);
Button cancel = (Button) d.findViewById(R.id.cancel);
bar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progresValue,
boolean fromUser) {
progress = progresValue;
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// Display the value in textview
size = seekBar.getMax();
}
});
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
paintView.setSize(progress);
d.dismiss();
}
});
cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
d.dismiss();
}
});
d.show();
}
private void showColorPickerDialogDemo() {
int initialColor = Color.WHITE;
ColorPickerDialog colorpick = new ColorPickerDialog(
FullImgTwoActivity.this, initialColor,
new OnColorSelectedListener() {
#Override
public void onColorSelected(int color) {
paintView.setColo(color);
}
});
colorpick.show();
}
public void Checkimage(View v) {
scaling.checktheimage(imageView1);
scaling.checkpaintimage(paintView);
boolean paint=scaling.bmapaint;
boolean image=scaling.bmapimage;
if(paint!=image){
AlertDialog.Builder al=new AlertDialog.Builder(FullImgTwoActivity.this);
al.setTitle("Please Try Again");
al.setIcon(R.drawable.checkno);
al.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
paintView.clear();
paintView.invalidate();
}
}) ;
al.setNegativeButton("NO",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Intent in=new Intent(FullImgTwoActivity.this, GridLayoutTwo.class);
startActivity(in);
finish();
}
});
AlertDialog dialog=al.create();
dialog.show();
}else {
AlertDialog.Builder al=new AlertDialog.Builder(FullImgTwoActivity.this);
al.setTitle("Please Go To Next Letter");
al.setIcon(R.drawable.checkno);
al.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Intent in=new Intent(FullImgTwoActivity.this, GridLayoutTwo.class);
startActivity(in);
finish();
}
}) ;
al.setNegativeButton("NO",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
paintView.clear();
paintView.invalidate();
}
});
AlertDialog dialog=al.create();
dialog.show();
}
}
//#Override
public boolean onCreateOptionsMenu1(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_full_img_two, menu);
return true;
}
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
return false;
}
}

ClassCastException while integrating google plus api inside a fragment

I followed all steps mentioned in developer.google.com to implement the googleplus api in my application.
I'm integrating the googleplus api in the fragment and i'm getting an ClassCastException when i run the code.
My Fragment Class:
import com.digiapes.apeonomy.animation.Positions;
import com.example.apeonomy.R;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.plus.Plus;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
public class Login extends Fragment implements OnGlobalLayoutListener,
OnClickListener, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
EditText UN, Pass;
View loginimage, loginusing, loginlayout;
ImageButton flogin, Glogin;
Button login1;
float f;
Positions pos = new Positions();
String name = "Harsha";
String pass = "hahaha";
private static final int RC_SIGNIN = 0;
private static boolean mSignInClicked;
private GoogleApiClient mGoogleApiClient;
private boolean mIntentInProgress;
private boolean mSignedIn;
private ConnectionResult mConnectionResult;
private Activity c;
private boolean mSignedInClicked;
// Login_Register Lg=new Login_Register();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View login = inflater.inflate(R.layout.login, container, false);
// TODO Auto-generated method stub
UN = (EditText) login.findViewById(R.id.UsernameL);
Pass = (EditText) login.findViewById(R.id.PassswordL);
loginimage = login.findViewById(R.id.LoginImage);
login1 = (Button) login.findViewById(R.id.Login);
loginusing = login.findViewById(R.id.loginusing);
loginlayout = login.findViewById(R.id.LoginLayout);
f = ((Login_Register) getActivity()).pos.getLIpos();
loginimage.getViewTreeObserver().addOnGlobalLayoutListener(this);
UN.getBackground().setAlpha(50);
Pass.getBackground().setAlpha(50);
ObjectAnimator.ofFloat(loginusing, View.ALPHA, 0, 1).setDuration(1000)
.start();
ObjectAnimator.ofFloat(loginlayout, View.ALPHA, 0, 1).setDuration(1000)
.start();
login.findViewById(R.id.googlepluslog).setOnClickListener(this);
login.findViewById(R.id.facebooklog).setOnClickListener(this);
return login;
}
#Override
public void onGlobalLayout() {
pos.setLIpos(loginimage.getY());
// TODO Auto-generated method stub
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
ObjectAnimator
.ofFloat(loginimage, View.TRANSLATION_Y,
f - loginimage.getY() - 130, 0).setDuration(300)
.start();
login1.setOnClickListener(this);
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks((ConnectionCallbacks) getActivity().getApplicationContext())
.addOnConnectionFailedListener(this).addApi(Plus.API, null)
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.Login:
if (UN.getText().length() == 0 || Pass.getText().length() == 0) {
Toast.makeText(getActivity(),
"Please enter valid Username and Password",
Toast.LENGTH_SHORT).show();
} else if (UN.getText().toString().equals(name)
&& Pass.getText().toString().equals(pass)) {
Intent intent = new Intent(getActivity()
.getApplicationContext(), Main.class);
startActivity(intent);
}
break;
case R.id.facebooklog:
break;
case R.id.googlepluslog:
signInWithGplus();
break;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (requestCode == RC_SIGNIN) {
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
}
private void signInWithGplus() {
// TODO Auto-generated method stub
if (!mGoogleApiClient.isConnecting()) {
mSignedIn = true;
resolveSignInerror();
}
}
private void resolveSignInerror() {
// TODO Auto-generated method stub
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(c, RC_SIGNIN);
} catch (SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// TODO Auto-generated method stub
if (!result.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), c, 0)
.show();
return;
}
if(!mIntentInProgress){
mConnectionResult=result;
if(mSignedInClicked)
resolveSignInerror();
}
}
#Override
public void onConnected(Bundle arg0) {
mSignedInClicked=false;
Toast.makeText(c, "Connected", Toast.LENGTH_SHORT).show();
// TODO Auto-generated method stub
}
#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
mGoogleApiClient.connect();
}
#Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
mGoogleApiClient.connect();
}
#Override
public void onStop() {
// TODO Auto-generated method stub
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
}
Getting error at this line:
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks((ConnectionCallbacks) getActivity().getApplicationContext())
.addOnConnectionFailedListener(this).addApi(Plus.API, null)
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
Logcat:
Solution given in Error implementing GoogleApiClient Builder for Android development didn't workout for me...
.addConnectionCallbacks((ConnectionCallbacks) getActivity().getApplicationContext())
That's wrong, the method accepts a class that implements GoogleApiClient.ConnectionCallbacks, use your Fragment instead of getActivity().getApplicationContext().

How to fetch data from Api into listview?

When i am trying to call the method "refresh" of main activity from another Api class,the method was called and also it shows some fatal errors.And it didn't change the adapter values.Can anyone give any idea to clear that.?
package com.example.hotspot;
import com.example.hotspot.HotspotApi;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ListView;
import android.widget.TextView;
public class HotSpot extends Activity {
TextView textview;
ListView listview;
HotspotAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hot_spot);
textview = (TextView) findViewById(R.id.textView1);
listview = (ListView) findViewById(R.id.listView1);
adapter = new HotspotAdapter(this);
listview.setAdapter(adapter);
new HotspotApi(adapter).execute();
}
public void refresh() {
System.out.println("refresh() is called");
adapter.notifyDataSetChanged();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.hot_spot, menu);
return true;
}
}
hotspot.java
package com.example.hotspot;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.hotspot.HotspotModel;
import com.example.hotspot.HotspotAdapter;
import android.os.AsyncTask;
public class HotspotApi extends AsyncTask<Void, Integer, Void> implements
Icommon {
public Boolean IsServerErr = false;
private JSONArray response_array;
String url = "some url";
HotspotAdapter adapter;
HotSpot hot;
public HotspotApi(HotspotAdapter adapter) {
this.adapter = adapter;
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
getresult();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
hot=new HotSpot();
hot.refresh();
super.onPostExecute(result);
}
void getresult() {
InternetManager manager = new InternetManager(url);
String category_jsonresponse = manager.URLRequest();
if (!manager.IsServerConn) {
IsServerErr = true;
}
if (category_jsonresponse != null) {
System.out.println("Hotspot_jsonresponse" + category_jsonresponse);
try {
response_array = new JSONArray(category_jsonresponse);
for (int i = 1; i < response_array.length(); i++) {
JSONObject image_object = response_array.getJSONObject(i);
HotspotModel h = new HotspotModel();
h.setId(image_object.getString("id") == null ? ""
: image_object.getString("id"));
h.setContent(image_object.getString("content") == null ? ""
: image_object.getString("content"));
h.setImg(image_object.getString("img") == null ? ""
: image_object.getString("img"));
h.setName(image_object.getString("name") == null ? ""
: image_object.getString("name"));
arraylist.add(h);
}
System.out.println("HotspotModelsize() is " + arraylist.size());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
HotspotAdapter.java
package com.example.hotspot;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class HotspotAdapter extends BaseAdapter implements Icommon{
private TextView textview;
private View view;
ImageView imageview;
private LayoutInflater inflater;
public HotspotAdapter(Context context ){
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return arraylist.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arraylist.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
if (arg1 == null) {
view = inflater.inflate(R.layout.custom_layout, null);
} else {
view = arg1;
}
textview = (TextView) view.findViewById(R.id.txt_content);
textview.setText(arraylist.get(arg0).getName());
return view;
}
}
In your HotSpotApi class you are creating a new HotSpot activity, this seems wrong. I guess that you are getting json data from internet and load it into a listview.
Solution:
In HotspotApi change following instead of calling activity method:
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
adapter.notfiyDatasetChanged();
}
Hope this will help you.
hot=new HotSpot(); ?? you cannot use like that! HotSpot is an activity, should be called by Framework for example, activitymanager. Or use startActivity() to show a activity.
Refresh method (adapter.notifyDataSetChanged();) will result in refresh of UI. However, hot = new HotSpot() will not call onCreated() method,which means the UI is not created. So it definitely results in the fatal error.
I'd never see anyone call an Activity with new operator.
You should reference the common process about how use a activity and adapter.

ListView OnItemClickListener Not working When ListView is inflated to onCreateInputView()

I am developing a Keyboard. When i am inflating a ListView in onCreateInputView() and returning same View(or parent View) to it. I have implemented setOnItemClickListener for the ListView i am not getting callback to it.
What might be the issue?
android framework doesn't work for listview for keyboard(InputMethodService) ?
FY Reference i am attaching the code please have look at it.
NOTE: i am able to get ontouchlistner of it.
package com.listkeyboard;
import java.util.ArrayList;
import android.content.Context;
import android.content.res.Configuration;
import android.inputmethodservice.InputMethodService;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class ListKeyBoardIME extends InputMethodService {
private LinearLayout mainLayout;
#Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
System.out.println("onCreate");
}
#Override
public View onCreateCandidatesView() {
// TODO Auto-generated method stub
System.out.println("onCreateCandidatesView");
return super.onCreateCandidatesView();
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
System.out.println("onDestroy");
}
#Override
public void onFinishInput() {
// TODO Auto-generated method stub
super.onFinishInput();
System.out.println("onFinishInput");
}
#Override
public void onFinishInputView(boolean finishingInput) {
// TODO Auto-generated method stub
super.onFinishInputView(finishingInput);
System.out.println("onFinishInputView");
}
#Override
public View onCreateInputView() {
// TODO Auto-generated method stub
System.out.println(" onCreateInputView");
LayoutInflater layoutInflater = (LayoutInflater) ListKeyBoardIME.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View mMainKeyboardLayout = layoutInflater.inflate(R.layout.keyboard_list_view, null);
mainLayout = (LinearLayout)mMainKeyboardLayout.findViewById(R.id.main_layout);
ListView listView = (ListView)mainLayout.findViewById(R.id.list);
ArrayList<Character> alphabets = new ArrayList<Character>();
for (char ch = 'a'; ch <= 'z'; ch++) {
alphabets.add(ch);
if (ch == 'n') {
break;
}
}
ArrayAdapter<Character> adapter = new ArrayAdapter<Character>(ListKeyBoardIME.this, android.R.layout.simple_list_item_1,alphabets);
listView.setAdapter(adapter);
listView.setItemsCanFocus(false);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Toast.makeText(getApplicationContext(), "on itemclicked clicked" , Toast.LENGTH_SHORT).show();
}
});
setInputView(mainLayout);
return mainLayout;
}
#Override
public void onStartCandidatesView(EditorInfo info, boolean restarting) {
// TODO Auto-generated method stub
super.onStartCandidatesView(info, restarting);
System.out.println("onStartCandidatesView ");
}
#Override
public void onStartInput(EditorInfo attribute, boolean restarting) {
// TODO Auto-generated method stub
super.onStartInput(attribute, restarting);
System.out.println("onStartInput ");
}
#Override
public void onStartInputView(EditorInfo info, boolean restarting) {
// TODO Auto-generated method stub
super.onStartInputView(info, restarting);
System.out.println("onStartInputView");
}
}
I am also face the same problem & after lot of searching when no answer work for me, i implement below code in my list adapter & its work for me. If anyone find any other better answer please let us know.
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});

Implementing Leadbolt in Android app

I am making my first Android app and I am trying to implement Leadbolt unlocker, I have done everything like Leadbolt documentation, but when I launch app it is always crashing. When I remove implement AdListener from public class FullActivity extends Activity implements AdListener then everything is working. App is crashing when Intent full = new Intent(GridActivity.this, FullActivity.class); and it is not even go to super.onCreate(savedInstanceState); breakpoint.
This is FullActivity.java:
import java.io.IOException;
import android.app.Activity;
import android.app.WallpaperManager;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import com.Leadbolt.AdController;
import com.Leadbolt.AdListener;
public class FullActivity extends Activity implements AdListener{
private AdController myController;
private String MY_LB_SECTION_ID="1111111";
private Integer[] mThumbIds = {
R.drawable.p1,
R.drawable.p2,
R.drawable.p3,
R.drawable.p4,
R.drawable.p5,
R.drawable.p6,
R.drawable.p7,
R.drawable.p8,
R.drawable.p9,
R.drawable.p10,
R.drawable.p11,
R.drawable.p12,
R.drawable.p13,
R.drawable.p14,
R.drawable.p15,
R.drawable.p16,
R.drawable.p17,
R.drawable.p18,
R.drawable.p19,
R.drawable.p20,
R.drawable.p21,
R.drawable.p22,
R.drawable.p23,
R.drawable.p24,
R.drawable.p25,
R.drawable.p26,
R.drawable.p27,
R.drawable.p28,
R.drawable.p29,
R.drawable.p30,
R.drawable.p31,
R.drawable.p32,
R.drawable.p33,
R.drawable.p34,
R.drawable.p35,
R.drawable.p36,
R.drawable.p37,
R.drawable.p38,
R.drawable.p39,
R.drawable.p40,
R.drawable.p41,
R.drawable.p42,
R.drawable.p43,
R.drawable.p44,
R.drawable.p45,
R.drawable.p46,
R.drawable.p47,
R.drawable.p48,
R.drawable.p49,
R.drawable.p50
};
Integer imageId;
TouchImageView touch;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
final Activity act = FullActivity.this;
final AdListener listener = FullActivity.this;
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
if (extras != null) {
imageId = extras.getInt("image");
touch = new TouchImageView(this);
Bitmap snoop = BitmapFactory.decodeResource(getResources(), mThumbIds[imageId]);
touch.setImageBitmap(snoop);
touch.setMaxZoom(4f); //change the max level of zoom, default is 3f
setContentView(touch);
}
final String PREFS_NAME = "AppPrefs";
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
int ad = settings.getInt("ad", 0);
if((imageId > 25)&&(ad < 1)){
touch.post(new Runnable() {
public void run(){
myController = new AdController(act, MY_LB_SECTION_ID,
listener);
myController.loadAd();
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.set_back:
setBack();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void setBack() {
WallpaperManager myWallpaperManager
= WallpaperManager.getInstance(getApplicationContext());
try {
myWallpaperManager.setResource(mThumbIds[imageId]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(FullActivity.this.getApplicationContext(), "Wallapers set!", Toast.LENGTH_SHORT).show();
}
public void onDestroy(){
myController.destroyAd();
super.onDestroy();
}
public void onAdClicked() {}
public void onAdClosed() {}
public void onAdCompleted() {
// TODO Auto-generated method stub
SharedPreferences settings = getSharedPreferences("AppPrefs", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("ad", 1);
// Commit the edits!
editor.commit();
}
public void onAdFailed() {
this.runOnUiThread(new Runnable() {
public void run() {
if(myController != null){
myController.destroyAd();
}
}
});
}
public void onAdLoaded() {}
public void onAdProgress() {}
}
We have made some adjustments to the code which should resolve this for you.
package com.mkstudio.hdwallpapers;
import java.io.IOException;
import android.app.Activity;
import android.app.WallpaperManager;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import com.Leadbolt.AdController;
import com.Leadbolt.AdListener;
public class FullActivity extends Activity{
private AdController myController;
private String MY_LB_SECTION_ID="729926945";
// references to our images
private Integer[] mThumbIds = {
R.drawable.p1,
R.drawable.p2,
R.drawable.p3,
R.drawable.p4,
R.drawable.p5,
R.drawable.p6,
R.drawable.p7,
R.drawable.p8,
R.drawable.p9,
R.drawable.p10,
R.drawable.p11,
R.drawable.p12,
R.drawable.p13,
R.drawable.p14,
R.drawable.p15,
R.drawable.p16,
R.drawable.p17,
R.drawable.p18,
R.drawable.p19,
R.drawable.p20,
R.drawable.p21,
R.drawable.p22,
R.drawable.p23,
R.drawable.p24,
R.drawable.p25,
R.drawable.p26,
R.drawable.p27,
R.drawable.p28,
R.drawable.p29,
R.drawable.p30,
R.drawable.p31,
R.drawable.p32,
R.drawable.p33,
R.drawable.p34,
R.drawable.p35,
R.drawable.p36,
R.drawable.p37,
R.drawable.p38,
R.drawable.p39,
R.drawable.p40,
R.drawable.p41,
R.drawable.p42,
R.drawable.p43,
R.drawable.p44,
R.drawable.p45,
R.drawable.p46,
R.drawable.p47,
R.drawable.p48,
R.drawable.p49,
R.drawable.p50
};
Integer imageId;
TouchImageView touch;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.full);
Bundle extras = getIntent().getExtras();
if (extras != null) {
imageId = extras.getInt("image");
touch = new TouchImageView(this);
Bitmap snoop = BitmapFactory.decodeResource(getResources(), mThumbIds[imageId]);
touch.setImageBitmap(snoop);
touch.setMaxZoom(4f); //change the max level of zoom, default is 3f
setContentView(touch);
}
final String PREFS_NAME = "SexyRec";
final Activity act = this;
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
int ad = settings.getInt("ad", 0);
if((imageId > 25)&&(ad < 1)){
touch.post(new Runnable() {
public void run(){
myController = new AdController(act, MY_LB_SECTION_ID, new AdListener() {
public void onAdProgress() {
// TODO Auto-generated method stub
}
public void onAdLoaded() {
// TODO Auto-generated method stub
}
public void onAdFailed() {
// TODO Auto-generated method stub
}
public void onAdCompleted() {
// TODO Auto-generated method stub
SharedPreferences settings = getSharedPreferences("SexyRec", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("ad", 1);
// Commit the edits!
editor.commit();
}
public void onAdClosed() {
// TODO Auto-generated method stub
}
public void onAdClicked() {
// TODO Auto-generated method stub
}
});
myController.loadAd();
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.set_back:
setBack();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void setBack() {
//chuckNorris.setResourceAsWallpaper(mThumbIds[imageId]);
WallpaperManager myWallpaperManager
= WallpaperManager.getInstance(getApplicationContext());
try {
myWallpaperManager.setResource(mThumbIds[imageId]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(FullActivity.this.getApplicationContext(), "Wallapers set!", Toast.LENGTH_SHORT).show();
}
public void onDestroy(){
myController.destroyAd();
super.onDestroy();
}
}

Categories

Resources