Save change String on restart in Android - android

Im building an app where I have an Array list with strings and a button.
When I press the button it deletes the string from the list (with string.remove) and display it in another activity..
The problem is that when I close the app and reopen it everything goes back to normal. How to save the changes made?
Here is the code:
public class TasksActivity extends AppCompatActivity {
private static ArrayList<String> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_tasks);
final Button tasksbtn = (Button) findViewById(R.id.btnfortasks);
Button checkTask = (Button) findViewById(R.id.remove_case);
final TextView tasksView = (TextView) findViewById(R.id.tasks_textView);
final ArrayList<String> tasks = new ArrayList<String>();
tasks.add("one");
tasks.add("two");
tasks.add("three");
tasks.add("four");
tasks.add("five");
tasks.add("six");
Collections.shuffle(tasks);
tasksView.setText(tasks.get(0));
assert tasksbtn != null;
tasksbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Collections.shuffle(tasks);
tasksView.setText(tasks.get(0));
}
});
checkTask.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(TasksActivity.this, CompletedTasks.class);
intent.putExtra("completedTasks", tasks.get(0));
tasks.remove(tasks.get(0));
startActivity(intent);
}
});
}
}
And the second Activity
public class CompletedTasks extends AppCompatActivity {
String completedTasks;
Global_Variable object = new Global_Variable();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_completed_tasks);
TextView completedTasksView = (TextView) findViewById(R.id.completed_tasks);
Intent intent = getIntent();
completedTasks = intent.getExtras().getString("completedTasks");
object.tasks.add(completedTasks + "\n");
String a = "";
for (int i = 0; i < object.tasks.size(); i++) {
a += object.tasks.get (i);
completedTasksView.setText(a);
Log.d("a", "a---------" + a);
}
}
}

You should probably give try to serialization. Please take look over below sample example.
public class SerializationDemo extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Person person = new Person();
person.setName("CoderzHeaven");
person.setAddress("CoderzHeaven India");
person.setNumber("1234567890");
//save the object
saveObject(person);
// Get the Object
Person person1 = (Person)loadSerializedObject(new File("/sdcard/save_object.bin")); //get the serialized object from the sdcard and caste it into the Person class.
System.out.println("Name : " + person1.getName());
}
public void saveObject(Person p){
try
{
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("/sdcard/save_object.bin"))); //Select where you wish to save the file...
oos.writeObject(p); // write the class as an 'object'
oos.flush(); // flush the stream to insure all of the information was written to 'save_object.bin'
oos.close();// close the stream
}
catch(Exception ex)
{
Log.v("Serialization Save Error : ",ex.getMessage());
ex.printStackTrace();
}
}
public Object loadSerializedObject(File f)
{
try
{
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
Object o = ois.readObject();
return o;
}
catch(Exception ex)
{
Log.v("Serialization Read Error : ",ex.getMessage());
ex.printStackTrace();
}
return null;
}
Person implements Serializable //Added implements Serializable
{
String name="";
private String number="";
private String address="";
private static final long serialVersionUID = 46543445;
public void setName(String name)
{
this.name = name;
}
public void setNumber(String number)
{
this.number = number;
}
public void setAddress(String address)
{
this.address = address;
}
public String getName()
{
return name;
}
public String getNumber()
{
return number;
}
public String getAddress()
{
return address;
}
}
}

You could try saving your changes to the SharedPreferences. Then when you resatrt your app, read the changes from your ShraredPreferences and apply it to your ListView or whatever you are using.
You can read more about SharedPreferences here: https://developer.android.com/training/basics/data-storage/shared-preferences.html

Related

How can intent or pass data through on click image in (slider Layout) android

I am a new application developer I try intent or pass data through on click image in (slider Layout) from first activity to the second activity. I try to intent (name) to second activity.
I now have a different set of images now, each one having its own name.if user clicking on the first image will intent or pass data of first image only.Also if user clicking on the five image will intent data of five image only.Like that what I want to do.
Please if anyone knows the answer help me.
import com.smarteist.autoimageslider.SliderLayout;
import com.smarteist.autoimageslider.SliderView;
public class SlidShowMain extends AppCompatActivity {
SliderLayout sliderLayout;
private List<SlidShowListData> list_dataList;
private JsonArrayRequest request;
private RequestQueue requestQueue;
private static final String HI ="http://=========/S.php";
TextView textView5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.slide_show_new);
sliderLayout = (SliderLayout) findViewById(R.id.imageSlider);
sliderLayout.setIndicatorAnimation(SliderLayout.Animations.WORM);
list_dataList=new ArrayList<>();
sliderLayout.setScrollTimeInSec(1);
textView5 =(TextView)findViewById(R.id.textView5);
SliderView sliderView = new SliderView(this);
setSliderViews();
}
private void setSliderViews() {
request = new JsonArrayRequest(HI, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSONObject jsonObject = null;
for (int i = 0; i < response.length(); i++) {
try {
jsonObject = response.getJSONObject(i);
SlidShowListData listData = new SlidShowListData listData = new SlidShowListData(jsonObject.getString("imageurl"),jsonObject.getString("name"),jsonObject.getString("id"));
String name = jsonObject.getString("id");
textView5.append(name + ", " +"\n\n");
list_dataList.add(listData);
} catch (JSONException e) {
e.printStackTrace();
}
}
setupdata(list_dataList);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(request);
}
private void setupdata(List<SlidShowListData> list_dataList) {
for (int i = 0; i <= 4; i++) {
final SlidShowListData ld = list_dataList.get(i);
SliderView view = new SliderView(getBaseContext());
view.setImageUrl(ld.getImageurl());
view.setImageUrl(ld.getname());
view.setImageScaleType(ImageView.ScaleType.CENTER_CROP);
final int finalI = i;
sliderLayout.addSliderView(view);
view.setOnSliderClickListener(new SliderView.OnSliderClickListener() {
#Override
public void onSliderClick(SliderView sliderView) {
Toast.makeText(SlidShowMain.this, "" + (sliderLayout.getCurrentPagePosition() + 1), Toast.LENGTH_SHORT).show();
}
});
}
}
}
public class SlidShowListData {
private String imageurl;
private String name;
private String id;
public SlidShowListData(String imageurl,String name,String id) {
this.imageurl = imageurl;
this.name = name;
this.id = id;
}
public String getImageurl() {
return imageurl;
}
public String getname() {
return name;
}
public String getId() {
return id;
}
}
implementation 'com.github.smarteist:autoimageslider:1.1.1'
implementation 'com.github.bumptech.glide:glide:4.7.1'
<?php
$con=mysqli_connect("localhost","=====","=====","show");
$sql="SELECT * FROM slhow";
$result=mysqli_query($con,$sql);
$data=array();
while($row=mysqli_fetch_assoc($result)){
$data[]=$row;
}
header('Content-Type:Application/json');
echo json_encode($data);
?>
I have tried to write it as follows:
holder.img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(context,HomeActivity.class);
intent.putExtra("id",======.=======()); // here problem
context.startActivity(intent);
I don't know what I should write or how on the second line into (====) to send an ID.must send the Id of image that user just clicks, not all ids of images
Anyone know solution , please help me
Use this code for sending data from FirstActivity:
val intent = Intent(this#FirstActivity, SecondActivity::class.java)
intent.putExtra("imagename", imageid)
startActivity(intent)
And this for delivering date in SecondActivity:
var imageid = intent.getStringExtra("imagename")

I want to save data in SecondActivity from FirstActivity using Room

I have three activities, I capture all data but one from DetailActivity upon button click and save in database using Room; My intention is to insert all these data into the database and start ReviewActivity so as to get the arraylist of reviews and also insert it in the database. Everything seems to work fine until when I want to view review offline because I believe it has been saved, reviews does not get loaded.
This is my DetailActivity,
TextView overview_tv; ImageView image_tv; TextView name_tv; TextView ratings; Context context; TextView release_date; ImageView backdrop_poster; private ExpandableHeightListView trailers; public static ArrayList<Youtube> youtube; public static ArrayList<Review> reviews; TrailerViewAdapter adapter; public static DataObject data; DataObject dataObject; ArrayList<Review> savedReview; private static final String IMAGE_URL = "http://image.tmdb.org/t/p/w185/"; private static final String THE_MOVIEDB_URL2 = "https://api.themoviedb.org/3/movie/"; private static final String MOVIE_QUERY2 = "api_key"; private static final String API_KEY2 = "6cc4f47bd4a64e0117e157b79072ae37"; private static String SEARCH_QUERY2 = "videos"; public static int movieId; Button viewReviews; Button favourite; String movieRating; private static final int YOUTUBE_SEARCH_LOADER = 23; private static final int REVIEW_SEARCH_LOADER = 24; File file; String name; String overview; String releaseDate; int switcher; public static ArrayList<Review> favouriteReviews; TextView trev; AppDatabase mDb; //Navigation arrow on the action bar #Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { NavUtils.navigateUpFromSameTask(this); } return super.onOptionsItemSelected(item); } #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail); mDb = AppDatabase.getInstance(getApplicationContext()); youtube = new ArrayList<Youtube>(); reviews = new ArrayList<Review>(); adapter = new TrailerViewAdapter(this, youtube); //Credit to Paolorotolo #github trailers = findViewById(R.id.expandable_list); trailers.setAdapter(adapter); trailers.setExpanded(true); //Navigation arrow on the acton bar; check also override onOptionsItemSelected ActionBar actionBar = this.getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); } context = getApplicationContext(); Intent intent = getIntent(); if (intent == null) { closeOnError(); } switcher = getIntent().getIntExtra("switch", 3); overview_tv = findViewById(R.id.overview); image_tv = findViewById(R.id.image); name_tv = findViewById(R.id.name); ratings = findViewById(R.id.ratings); release_date = findViewById(R.id.release_date); backdrop_poster = findViewById(R.id.backdrop_poster); trev = findViewById(R.id.review_show); viewReviews = findViewById(R.id.review_button); favourite = findViewById(R.id.favourite_button); addListenerOnRatingBar(ratings); if (switcher != 2) { favourite.setVisibility(View.INVISIBLE); dataObject = (DataObject) getIntent().getParcelableExtra("array"); final String favouriteName = dataObject.getName(); final String favouriteOverview = dataObject.getOverview(); final String favouriteReleaseDate = dataObject.getReleaseDate(); ArrayList<Youtube> savedTrailer = dataObject.getTrailers(); savedReview = dataObject.getMovieReviews(); movieRating = dataObject.getRating(); name_tv.setText(favouriteName); overview_tv.setText(favouriteOverview); ratings.setText("Rating: " + movieRating); release_date.setText("Release Date: " + favouriteReleaseDate);// Toast.makeText(this, "Testing Reviews " + savedReview.get(0).getAuthor(), Toast.LENGTH_SHORT).show(); String imagePath = name_tv.getText().toString() + "0i"; String backdropPath = name_tv.getText().toString() + "1b"; try { DataObjectAdapter.downloadImage(imagePath, image_tv, this); } catch (Exception e) { e.printStackTrace(); } try { DataObjectAdapter.downloadImage(backdropPath, backdrop_poster, context); } catch (Exception e) { e.printStackTrace(); } if (savedTrailer != null) { TrailerViewAdapter lv = new TrailerViewAdapter(DetailActivity.this, savedTrailer); trailers.setAdapter(lv); switcher = 3; } } else { name = getIntent().getStringExtra("Name"); overview = getIntent().getStringExtra("Overview"); final String image = getIntent().getStringExtra("Image"); movieId = getIntent().getIntExtra("movieId", 1); final String backdrop = getIntent().getStringExtra("backdrop"); releaseDate = getIntent().getStringExtra("releaseDate"); movieRating = getIntent().getStringExtra("rating"); Log.i("this", "switch " + switcher); name_tv.setText(name); overview_tv.setText(overview); ratings.setText("Rating: " + movieRating); release_date.setText("Release Date: " + releaseDate); //load backdrop poster Picasso.with(context) .load(IMAGE_URL + backdrop) .fit() .placeholder(R.drawable.placeholder_image) .error(R.drawable.placeholder_image) .into(backdrop_poster); Picasso.with(context) .load(IMAGE_URL + image) .fit() .placeholder(R.drawable.placeholder_image) .error(R.drawable.placeholder_image) .into(image_tv); getSupportLoaderManager().initLoader(YOUTUBE_SEARCH_LOADER, null, this); //getSupportLoaderManager().initLoader(REVIEW_SEARCH_LOADER, null, this); //loadTrailers(); //loadReviews(); //populateKeys(); } /** * Here manages the views(list) for reviews */ viewReviews.setOnClickListener(new View.OnClickListener() { #Override public void onClick(View v) { if (switcher == 3) { startActivity(new Intent(DetailActivity.this, ReviewActivity.class) .putExtra("switch", 3)); } else { Log.i("this", "I am from initial" + switcher); startActivity(new Intent(DetailActivity.this, ReviewActivity.class).putExtra("id", movieId)); } } } ); favourite.setOnClickListener(new View.OnClickListener() { #Override public void onClick(View v) { data = new DataObject(); data.setName(name); data.setOverview(overview); data.setRating(movieRating); data.setReleaseDate(releaseDate); data.setTrailers(youtube);// data.setMovieReviews(reviews); try { saveImage(name_tv.getText().toString() + "0i", image_tv); saveImage(name_tv.getText().toString() + "1b", backdrop_poster); } catch (IOException e) { e.printStackTrace(); } Toast.makeText(context, "The movie is saved as a favourite", Toast.LENGTH_LONG).show(); AppExecutors.getInstance().diskIO().execute(new Runnable() { #Override public void run() { mDb.dataDao().insertData(data); } }); startActivity(new Intent(DetailActivity.this, ReviewActivity.class).putExtra("id", movieId) .putExtra(ReviewActivity.EXTRA_DATA_ID, 20)); } } ); }
And my ReviewActivity
public class ReviewActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<ArrayList<Review>>{ public static ArrayList<Review> reviews; public static List<DataObject> favouriteReviews; public static RecyclerView reviewList; ArrayList<Review> r; private static final int REVIEW_SEARCH_LOADER = 24; private static final String MOVIE_QUERY3 = "api_key"; private static final String API_KEY3 = "6cc4f47bd4a64e0117e157b79072ae37"; private static String SEARCH_QUERY3 = "reviews"; private static final String THE_MOVIEDB_URL3 = "https://api.themoviedb.org/3/movie/"; private static int movId; public static final String EXTRA_DATA_ID = "extraDataId"; private static final int DEFAULT_TASK_ID = -1; private int mTaskId = DEFAULT_TASK_ID; DataObject data1; AppDatabase mDb; ReviewAdapter revAdapter; int loaderSwitch; #Override protected void onResume() { super.onResume(); } #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_review); mDb = AppDatabase.getInstance(getApplicationContext()); reviews = new ArrayList<Review>(); favouriteReviews = new ArrayList<DataObject>(); reviewList = findViewById(R.id.review_list); LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext()); reviewList.setLayoutManager(layoutManager); reviewList.setHasFixedSize(true); int switcher = getIntent().getIntExtra("switch", 1); Intent intent = getIntent(); if (intent == null) { finish(); } Log.i("this", "swithcer " + switcher); Log.i("this loader", "Loader " + loaderSwitch); if (switcher == 3){ DataObject dataObject = (DataObject) getIntent().getParcelableExtra("ArrayOfReviews"); if (dataObject != null){ ArrayList<Review> movieReviews = dataObject.getMovieReviews(); Toast.makeText(this, "There are reviews saved", Toast.LENGTH_LONG).show(); revAdapter = new ReviewAdapter(this, movieReviews ); reviewList.setAdapter(revAdapter); } } else { movId = getIntent().getIntExtra("id", 20); revAdapter = new ReviewAdapter(this, reviews); reviewList.setAdapter(revAdapter); loadReviews(); //populateReview(); } DividerItemDecoration decoration = new DividerItemDecoration(this, VERTICAL); reviewList.addItemDecoration(decoration); } #Override protected void onStart() { super.onStart(); //loadReviews(); } public static URL buildUrl3(String stringUrl) { Uri uri = Uri.parse(THE_MOVIEDB_URL3).buildUpon() .appendPath(stringUrl) .appendPath(SEARCH_QUERY3) .appendQueryParameter(MOVIE_QUERY3, API_KEY3) .build(); URL url = null; try { url = new URL(uri.toString()); } catch (MalformedURLException exception) { Log.e(TAG, "Error creating URL", exception); } return url; } public void loadReviews(){ // COMPLETED (19) Create a bundle called queryBundle Bundle queryBundle = new Bundle(); // COMPLETED (20) Use putString with SEARCH_QUERY_URL_EXTRA as the key and the String value of the URL as the value// queryBundle.putString(SEARCH_QUERY_URL_EXTRA, url.toString()); // COMPLETED (21) Call getSupportLoaderManager and store it in a LoaderManager variable LoaderManager loaderManager = getSupportLoaderManager(); // COMPLETED (22) Get our Loader by calling getLoader and passing the ID we specified Loader<ArrayList<Review>> movieReviews = loaderManager.getLoader(REVIEW_SEARCH_LOADER); // COMPLETED (23) If the Loader was null, initialize it. Else, restart it. if (movieReviews == null) { loaderManager.initLoader(REVIEW_SEARCH_LOADER, queryBundle, this); } else { loaderManager.restartLoader(REVIEW_SEARCH_LOADER, queryBundle, this); } } #Override public Loader<ArrayList<Review>> onCreateLoader(int id, Bundle args) { return new AsyncTaskLoader<ArrayList<Review>>(this) { #Override protected void onStartLoading() { super.onStartLoading(); forceLoad(); } #Override public ArrayList<Review> loadInBackground() { String g = String.valueOf(movId); // Create URL object URL url = buildUrl3(g); // Perform HTTP request on the URL and receive a JSON response back String jsonResponse = ""; try { jsonResponse = getResponseFromHttpUrl(url); } catch (Exception e) { e.printStackTrace(); } reviews = MovieJsonUtils.parseReview(jsonResponse); return reviews; } }; } #Override public void onLoadFinished(Loader<ArrayList<Review>> loader, ArrayList<Review> dat) { if (reviews != null) { Intent intent = getIntent(); if (intent != null && intent.hasExtra(EXTRA_DATA_ID)) { //mButton.setText(R.string.update_button); if (mTaskId == DEFAULT_TASK_ID) { mTaskId = intent.getIntExtra(EXTRA_DATA_ID, DEFAULT_TASK_ID); AppExecutors.getInstance().diskIO().execute(new Runnable() { #Override public void run() { data.setMovieReviews(reviews); mDb.dataDao().updateData(data); //mDb.dataDao().insertData(data); final List<DataObject> task = mDb.dataDao().loadById(mTaskId); runOnUiThread(new Runnable() { #Override public void run() { populateUI(task); } }); } }); } } else { ReviewAdapter lv = new ReviewAdapter(ReviewActivity.this, reviews); reviewList.setAdapter(lv); } } } #Override public void onLoaderReset(Loader<ArrayList<Review>> loader) { }
Data gets loaded from MainActivity, the saved data is passed on to other activities as a parcellable bundle via intent, the passed data is displayed in DetailActivity but not in ReviewActivity.
Alternatively, if I can load reviews alongside YouTube keys from DetailActivity, I believe I can handle the database issue from there, but two Loaders wouldn't just work together, the app crashes; I am aware two AsyncTasks concurrently run together solved this problem, but I prefer to use Loaders because of performance on configuration change

How to pass asynctask to another activity in android?

I'm try to writing an online game with a socket connection.
So I use asynctask to make a socket connection.
SocketServer.java
public class SocketServer{
private MyCustomListener listener;
private String ip = "127.0.0.1";
private int port = 4444;
#SuppressWarnings("unused")
private Context context;
private SocketAsync socketAsync;
private String dataInput, username;
public SocketServer(Context context) {
this.context = context;
}
public void setOnRecieveMsgListener(MyCustomListener listener) {
this.listener = listener;
}
public void connect() {
socketAsync = new SocketAsync();
socketAsync.execute();
}
public void sentData(String x, String y, String z) {
dataInput = null;
JSONObject object = new JSONObject();
// JSON Encode
socketAsync.sentJSON(object);
}
private class SocketAsync extends AsyncTask<Void, Void, String> {
private Socket socket;
private PrintWriter printWriter;
#Override
protected String doInBackground(Void... params) {
try {
socket = new Socket(InetAddress.getByName(ip),port);
OutputStreamWriter streamOut = new OutputStreamWriter(socket.getOutputStream(), "UTF-8");
printWriter = new PrintWriter(streamOut);
streamOut.flush();
BufferedReader streamIn = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
Looper.prepare();
while(socket.isConnected()) {
try {
dataInput = streamIn.readLine();
listener.onRecieveMessage(new MyListener(dataInput));
}
catch(Exception e) {}
}
Looper.loop();
}
catch(Exception e) {}
return null;
}
public void sentJSON(JSONObject object) {
if(socket.isConnected()) {
try {
printWriter.println(object.toString());
printWriter.flush();
}
catch(Exception e) {}
}
}
}
}
Login.class
public class Login extends Activity implements MyCustomListener {
JSONObject object;
SocketServer socketserver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
socketserver = new SocketServer(this);
socketserver.setOnRecieveMsgListener(this);
socketserver.connect();
button();
}
private void button() {
Button loginBt = (Button)findViewById(R.id.login_bt);
final EditText un = (EditText)findViewById(R.id.username);
final EditText ps = (EditText)findViewById(R.id.password);
final String[] logindata = new String[2];
loginBt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
logindata[0] = un.getText().toString();
logindata[1] = ps.getText().toString();
socketserver.setUsername(logindata[0]);
socketserver.sentData("SERVER", "TEST", "login");
}
});
}
private void toMainScreen() {
Intent x = new Intent(this,Main.class);
startActivity(x);
}
#Override
public void onRecieveMessage(MyListener ml) {
try {
JSONObject json = new JSONObject(ml.getMsgStr());
System.out.println(json.getString("content"));
if(json.getString("content").equals("TRUE")) {
toMainScreen();
}
else
Toast.makeText(getApplicationContext(), "Login Fail", Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
Log.e("## JSON DECODE", e.toString());
e.printStackTrace();
}
}
}
Main.class
public class Main extends Activity implements MyCustomListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//do some thing
}
#Override
public void onRecieveMessage(MyListener ml) {
System.out.println("MAIN : " + ml.getMsgStr());
}
}
so how can I pass object "socketserver" from login class to main class?
or is there an other way to do something like this?
sorry for my poor english.
You should not try to pass an instance of SocketServer around. One of it's properties is context which means you should not used it outside the original context it was created in (i.e. activity it was created in) or you'll have memory leaks.
Your SocketServer class needs IP and port. This is the kind of information that you should pass between activities and then use that to create another instance of your SocketServer class.

Android Intent after onpostexecute fails to start

I have a registration system. The registration is working fine. My main problem is: I would like to start MainActivity.java after logging in. After sending the login data to the Server, the Server checks in Database if it matches and sends out an int (0 for unmatched) and (1 for success). This works great as well. But if i want to start the Intent after onPostExecute Method it gives out an Error:
FATAL EXCEPTION: main
java.lang.NullPointerException
at android.app.Activity.startActivityForResult
...
This is my StartPage which exectues my AsyncTask Class. And receives success or unmatched in the Method getLoginMessage().
public class LoginPage extends Activity {
String userName;
String password;
String sendProtocolToServer;
static String matched = null;
static String unmatched;
static Context myCtx;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loginpage);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Button login = (Button) findViewById(R.id.loginBtn);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
handleLogin();
}
});
Button register = (Button) findViewById(R.id.registerBtn);
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent openMainActivityRegister = new Intent(
"com.example.fotosharing.REGISTERPAGE");
startActivity(openMainActivityRegister);
}
});
}
private void handleLogin() {
EditText editTextBox = (EditText) findViewById(R.id.EditTextUser);
EditText passwordTextBox = (EditText) findViewById(R.id.EditTextPassword);
userName = editTextBox.getText().toString();
password = passwordTextBox.getText().toString();
if (!userName.equals("") && !password.equals("")) {
sendProtocolToServer = "login" + "#" + userName + "#" + password;
ConnectToServer cts = new ConnectToServer(sendProtocolToServer);
cts.execute();
} else {
Toast.makeText(this, "Fill in Username and Password to login",
Toast.LENGTH_LONG).show();
}
}
public void getLoginMessage(String receivedMessage) {
if (receivedMessage.equals("success")) {
Intent openMainActivity = new Intent(
"com.example.fotosharing.TIMELINEACTIVITY");
openMainActivity.clone();
startActivity(openMainActivity);
}
if (receivedMessage.equals("unmatched")) {
Toast.makeText(this, "Password or username incorrect.", Toast.LENGTH_LONG).show();
}
}
}
This is my Async-Task class which receives Data from my Java-Server, and checks if it was an successful or an unmatched login. In onPostExecute im calling a Method in the LoginPage.class, which handles the Intent (here comes the Error).
public class ConnectToServer extends AsyncTask<Void, Void, String> {
public Context myCtx;
static Socket socket;
String sendStringToServer;
int protocolId = 0;
private static DataOutputStream DOS;
private static DataInputStream DIS;
StringBuffer line;
int j = 1;
String value;
static String res = null;
public ConnectToServer(String sendStringToServer) {
this.sendStringToServer = sendStringToServer;
}
public ConnectToServer(int i) {
this.protocolId = i;
}
public ConnectToServer() {
}
public ConnectToServer(Context ctx) {
this.myCtx = ctx;
}
protected String doInBackground(Void... arg0) {
try {
socket = new Socket("192.168.1.106", 25578);
DOS = new DataOutputStream(socket.getOutputStream());
if (protocolId == 1) {
DOS.writeUTF("pictureload");
protocolId = 0;
} else {
DOS.writeUTF(sendStringToServer);
}
res = receive();
// DOS.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("RES: " + res);
return res;
}
public String receive() {
String receiveResult = null;
if (socket.isConnected()) {
try {
BufferedReader input = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
DIS = new DataInputStream(socket.getInputStream());
int msg_received = DIS.readInt();
System.out.println("SERVER: " + msg_received);
if (msg_received == 1) {
receiveResult = "success";
System.out.println("IF (success): " + receiveResult);
}
if (msg_received == 0) {
receiveResult = "unmatched";
System.out.println("ELSE IF (unmatched): "
+ receiveResult);
}
} catch (IOException e) {
e.printStackTrace();
}
}
// ***** return your accumulated StringBuffer as string, not current
// line.toString();
return receiveResult;
}
protected void onPostExecute(String result1) {
if (result1 != null) {
if (result1.equals("success") || result1.equals("unmatched")) {
sendToLoginPage(result1);
}
}
}
private void sendToLoginPage(String result1) {
System.out.println("sendtologi " + result1);
LoginPage lp = new LoginPage();
lp.getLoginMessage(result1);
}
}
This is the class I want to start when it was a successful login.
What am I doing wrong?
public class MainActivity extends SherlockFragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
ActionBar actionbar = getSupportActionBar();
actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionbar.setBackgroundDrawable(new ColorDrawable(Color.BLACK));
actionbar.setStackedBackgroundDrawable(new ColorDrawable(Color.parseColor("#91d100")));
ActionBar.Tab Frag1Tab = actionbar.newTab().setText("Home");
ActionBar.Tab Frag2Tab = actionbar.newTab().setText("Share Photo");
Fragment Fragment1 = new TimelineActivity();
Fragment Fragment2 = new CameraActivity();
Frag1Tab.setTabListener(new MyTabsListener(Fragment1));
Frag2Tab.setTabListener(new MyTabsListener(Fragment2));
actionbar.addTab(Frag1Tab);
actionbar.addTab(Frag2Tab);
}
}
You cannot just create instance of your activity with new keyword, like this:
private void sendToLoginPage(String result1) {
System.out.println("sendtologi " + result1);
LoginPage lp = new LoginPage();
lp.getLoginMessage(result1);
}
This is wrong and it is probably why you are getting error. Code you posted is quite complex, so i am not sure if there are any other problems.
This is how it should be done:
So... Since you probably have ConnectToServer asyncTask in separate file, you need pass events or data to your LoginPage activity. For this purpose, you should use event listener, like this:
First, create interface that will represent communication between your ConnectToServer and your LoginPage.
public interface LoginResultListener {
public void getLoginMessage(String receivedMessage);
}
Now, make your LoginPage activity implement this interface:
public class LoginPage extends Activity implements LoginResultListener {
...
}
Now, update your ConnectToServer asyncTask, so that it uses LoginResultListener to communicate login result to your activity, like this:
public class ConnectToServer extends AsyncTask<Void, Void, String> {
private LoginResultListener listener;
...
public void setListener(LoginResultListener listener) {
this.listener = listener;
}
...
private void sendToLoginPage(String result1) {
System.out.println("sendtologi " + result1);
//THIS IS WHERE YOU DID WRONG
listener.getLoginMessage(result1);
}
...
}
Now finally, when you create new ConnectToServer async task from your activity, you need to set listener that will handle events when user logs in. Since you implemented this interface in your activity, you will send your activity object as listener parameter, see below:
ConnectToServer cts = new ConnectToServer(sendProtocolToServer);
// THIS IS IMPORTANT PART - 'this' refers to your LoginPage activity, that implements LoginResultListener interface
cts.setListener(this);
cts.execute();

Android: Passing extra from one activity to another activity

I have a JSON file which is populated to an activity (Main.java).
This Activity shows 3 random images from the URL on my JSON entries.
What I wanna do is: I have 13 different entries on the my JSON, whenever I click the shown random picture it goes to another activity (ProjectDetail.java) containing the picture,title,and description depends on the item I click based on its entry on the JSON.
What do I have in is by using extra by I dont know exactly how to perform that since I'm using JSON. What should I add into my top_listener method on my Main class and what should I add into my ProjectDetail class?
Thank you.
Main.java
public class Main extends Activity {
/** Called when the activity is first created. */
ArrayList<Project> prjcts=null;
private ImageThreadLoader imageLoader = new ImageThreadLoader();
private final static String TAG = "MediaItemAdapter";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
prjcts = new ArrayList<Project>();
WebService webService = new WebService("http://liebenwald.spendino.net/admanager/dev/android/projects.json");
Map<String, String> params = new HashMap<String, String>();
params.put("var", "");
String response = webService.webGet("", params);
try
{
Type collectionType = new TypeToken<ArrayList<Project>>(){}.getType();
List<Project> lst= new Gson().fromJson(response, collectionType);
for(Project l : lst)
{
prjcts.add(l);
ConstantData.projectsList.add(l);
}
}
catch(Exception e)
{
Log.d("Error: ", e.getMessage());
}
final Button project = (Button) findViewById(R.id.btn_projectslist);
final Button infos = (Button) findViewById(R.id.btn_infos);
final Button contact = (Button) findViewById(R.id.btn_contact);
project.setOnClickListener(project_listener);
infos.setOnClickListener(infos_listener);
contact.setOnClickListener(contact_listener);
ImageView image1;
ImageView image2;
ImageView image3;
try {
image1 = (ImageView)findViewById(R.id.top1);
image2 = (ImageView)findViewById(R.id.top2);
image3 = (ImageView)findViewById(R.id.top3);
} catch( ClassCastException e ) {
Log.e(TAG, "Your layout must provide an image and a text view with ID's icon and text.", e);
throw e;
}
Bitmap cachedImage1 = null;
Bitmap cachedImage2 = null;
Bitmap cachedImage3 = null;
//randomize the index of image entry
int max = prjcts.size();
List<Integer> indices = new ArrayList<Integer>(max);
for(int c = 0; c < max; ++c)
{
indices.add(c);
}
int arrIndex = (int)((double)indices.size() * Math.random());
int randomIndex1 = indices.get(arrIndex);
indices.remove(arrIndex);
int randomIndex2 = indices.get(arrIndex);
indices.remove(arrIndex);
int randomIndex3 = indices.get(arrIndex);
indices.remove(arrIndex);
setImage(cachedImage1, image1, prjcts.get(randomIndex1));
setImage(cachedImage2, image2, prjcts.get(randomIndex2));
setImage(cachedImage3, image3, prjcts.get(randomIndex3));
image1.setOnClickListener(top_listener);
image2.setOnClickListener(top_listener);
image3.setOnClickListener(top_listener);
}
public void setImage(Bitmap cachedImage, final ImageView image, Project pro)
{
//Bitmap cachedImage1 = null;
try {
cachedImage = imageLoader.loadImage(pro.smallImageUrl, new ImageLoadedListener()
{
public void imageLoaded(Bitmap imageBitmap)
{
image.setImageBitmap(imageBitmap);
//notifyDataSetChanged();
}
});
} catch (MalformedURLException e) {
Log.e(TAG, "Bad remote image URL: " + pro.smallImageUrl, e);
}
if( cachedImage != null ) {
image.setImageBitmap(cachedImage);
}
}
private OnClickListener top_listener = new OnClickListener() {
public void onClick(View v) {
Intent top = new Intent(Main.this, InfosActivity.class);
startActivity(top);
}
};
ProjectDetail.java
public class ProjectDetail extends Activity implements OnClickListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.project);
Button weitersagen = (Button) findViewById(R.id.btn_weitersagen);
weitersagen.setOnClickListener(this);
Button sms = (Button) findViewById(R.id.btn_sms_spenden);
sms.setOnClickListener(this);
int position = getIntent().getExtras().getInt("spendino.de.ProjectDetail.position");
Project project = ConstantData.projectsList.get(position);
try {
ImageView projectImage = (ImageView)findViewById(R.id.project_image);
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(project.bigImageUrl).getContent());
projectImage.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
TextView project_title = (TextView)findViewById(R.id.txt_project_title);
project_title.setText(project.project_title);
TextView organization_title = (TextView)findViewById(R.id.txt_organization_title);
organization_title.setText(Html.fromHtml("von " +project.organization_title));
TextView project_description = (TextView)findViewById(R.id.txt_project_description);
project_description.setText(Html.fromHtml(project.project_description));
}
I also have this ConstantData.java, the index which holds my JSON properties:
public class ConstantData{
public static String project_title = "project title";
public static String organization_title = "organization title";
public static String keyword = "keyword";
public static String short_code = "short code";
public static String project_description = "description";
public static String smallImageUrl = "smallImageUrl";
public static String bigImageUrl = "bigImageUrl";
public static String price= "price";
public static String country= "country";
public static ArrayList<Project> projectsList = new ArrayList<Project>();
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeString(project_title);
out.writeString(organization_title);
out.writeString(keyword);
out.writeString(short_code);
out.writeString(project_description);
out.writeString(smallImageUrl);
out.writeString(bigImageUrl);
out.writeString(price);
out.writeString(country);
}
public static final Parcelable.Creator<ConstantData> CREATOR
= new Parcelable.Creator<ConstantData>() {
public ConstantData createFromParcel(Parcel in) {
return new ConstantData(in);
}
public ConstantData[] newArray(int size) {
return new ConstantData[size];
}
};
private ConstantData(Parcel in) {
project_title = in.readString();
organization_title = in.readString();
keyword = in.readString();
short_code = in.readString();
project_description = in.readString();
smallImageUrl = in.readString();
bigImageUrl = in.readString();
price = in.readString();
country = in.readString();
}
}
You could make the class ConstantData serializable by extending from Parcelable and implementing a couple of methods (see the documentation). Then you could pass a constantData instance as an extra by doing
intent.putExtra("jsonData", constantDataInstance);
and retrieving it from the other activity (in it's onCreate() method) with
getIntent().getExtras().getParcelable("jsonData");
Otherwise you could just past as extra every field independently, but it would be a mess. This way is not only more easy to read and everything, but "well designed".
To pass information from one activity to another when you start the new one you do the following:
Intent top = new Intent(Main.this, InfosActivity.class);
Bundle b = new Bundle();
b.putString("key1", "value2");
b.putString("key2", "value2");
b.putString("key3", "value3");
top.putExtras(b);
startActivity(top);
Then in the newly started activity, in the onCreate() put the following:
Bundle b = getIntent().getExtras();
b.get("key1");
b.get("key2");
b.get("key3");
This will get the values from the previous activity by using the key you provided.
For more complex objects you should extend Parcelable (probably what you'll need) and then use:
b.putParcelable("Key4", yourParcelableObject);
And in your onCreate()
b.getParcelable("Key4");
I hope this helps.
Use gson to parse the json to Java. Then you can use Wagon to move the extras around with ease.
GSON:
https://github.com/google/gson
Wagon:
https://github.com/beplaya/Wagon

Categories

Resources