I am trying to send 'id' from my fragment activity to an activity and parsing json data based on this 'id' field.
I am successfully sending data from fragment to TourDetail activity, but it is not parsing the json based on same 'id'. The code is not reaching second try block as I examined it using toasts.
Although the same activity(TourDetailActivity.java) is working fine when I pass 'id' from some other activity. Say, if I passed 'id' from jsonuseactivity.java, it is received successfully by TourDetailActivity.java and the respective json result is generated and the appropriate result is displayed.
But if the same 'id' is passed from the fragment activity, it is although receiving the 'id' but not generating the json and no required results based on json are being generated.
TourDetailActivity.java
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tour_detail);
Intent intent = getIntent();
String rcvid = intent.getStringExtra("id");
Toast.makeText(getApplicationContext(), rcvid, Toast.LENGTH_LONG).show();
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("tourid", rcvid));
String response = null;
// call executeHttpPost method passing necessary parameters
try {
Toast.makeText(getApplicationContext(), "in try block", Toast.LENGTH_LONG).show();
response = CustomHttpClient.executeHttpPost(
//"http://129.107.187.135/CSE5324/jsonscript.php", // your ip address if using localhost server
"http://www.futurolicht.com/jsontour.php", // in case of a remote server
postParameters);
String result = response.toString();
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
//parse json data
try {
Toast.makeText(getApplicationContext(), "in 2nd try block", Toast.LENGTH_LONG).show();
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
tname = (TextView) findViewById(R.id.txt_tourtitle);
td = (TextView) findViewById(R.id.txt_day);
tn = (TextView) findViewById(R.id.txt_night);
tdest = (TextView) findViewById(R.id.txt_tourdetail_dest);
btn = (Button) findViewById(R.id.btn_tourdetail);
btn.setOnClickListener(this);
tname.setText(json_data.getString("tour_name"));
tn.setText(json_data.getString("nights"));
td.setText(json_data.getString("days"));
name = json_data.getString("tour_name");
n = json_data.getString("nights");
d = json_data.getString("days");
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
This is my Fragmentone.java's onCreate() method code:
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_one, null);
String fontPath = "fonts/ox.ttf";
b1 = (Button)root.findViewById(R.id.featured_btn1);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String id = "34";
Intent intent = new Intent(getActivity(), TourDetailActivity.class);
intent.putExtra("id", id);
getActivity().startActivity(intent);
}
});
I didn't know what actually happened as above code seems okay to me. Instead of sending data, you can make the variable as Static and access that variable in other class like Fragmentone.id. This will definitely work.
Also did you try to catch that id in onStart() instead of onCreate() ? It is convenient to check if there are arguments passed to the fragment in startup
Related
I'm using intent to pass the string value to next Activity where I use getStringExtra to get the Value. The value is is User Contact no. in 10 digit which is in numeric value. when I setText in textview then It display the correct format but when I use intent on onclicklistener to open dialpad then instead of no, some random no. appears and in 4 digit also
Here I use to pass string
intent.putExtra(MOBILE, g.getSellermobile());
and I receive it by
tutor_mobile = intent.getStringExtra(MOBILE);
when I set it in textview as
TextView contact = (TextView) findViewById(R.id.tutor_near);
contact.setText(tutor_mobile);
It display correct format eg 9868336847
but when I use intent to open dialpad as
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:"+String.valueOf(tutor_mobile)));
startActivity(intent);
I'm using below code to get the mobile no.
etMobile = (EditText) findViewById(R.id.user_mobile);
String sellermobile = etMobile.getText().toString();
and In class file I have
package com.nepalpolice.filmyduniya.maincategory;
public class location {
public String sellermobile;
// public Uri uri;
public location( String sellermobile) {
this.sellermobile = sellermobile;
// this.uri = uri;
}
public String getSellermobile() { return sellermobile;}
}
}
Then in activity I have
public static final String MOBILE = "other_mobile";
and
intent.putExtra(MOBILE, g.getSellermobile());
and in next activity I have
tutor_mobile = intent.getStringExtra(MOBILE); and
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:"+String.valueOf(tutor_mobile)));
startActivity(intent);
Then random no. in 4 digit appears.
Then in activity I have
Please Help.
Your tutor_mobile is a String value, but thr you rearrange it toString:
intent.setData(Uri.parse("tel:"+String.valueOf(tutor_mobile)));
May be it's not a error, but it's strange. And what do you want to display in dialpad?
try {
Intent callIntent = new Intent(Intent.ACTION_DIAL);
callIntent.setData(Uri.parse("tel:" + "string format number"));
startActivity(callIntent);
} catch (Exception e) {
Log.d("Response", e.toString());
}
I want to make the login button to dispatch into 2 different activities using the flag column on the database??
if the tenant logged in it will redirect to the tenant activity
and when the landlord is logged in it will redirect to the other activity?
public void onResponse(String response) {
Log.e(TAG, "Register Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
success = jObj.getInt(TAG_SUCCESS);
// Check for error node in json
if (success == 1) {
String username = jObj.getString(TAG_USERNAME);
String id = jObj.getString(TAG_ID);
Log.e("Successfully Login!", jObj.toString());
Toast.makeText(getApplicationContext(), jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean(session_status, true);
editor.putString(TAG_ID, id);
editor.putString(TAG_USERNAME, username);
editor.commit();
// go to main activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra(TAG_ID, id);
intent.putExtra(TAG_USERNAME, username);
finish();
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(),
jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
Inside the onClickListener() method of your log in button,you can put a if() statement.
Steps To Do this
1. Get the data from the username and password field and use that in your query to retrieve the data from the database
2. Store the data you retrieved in a String like below because you will get only one row:
String flag = cursor.getString(7); //skipping the cursor and other database part
3. Now you can put the if() statement in the onClickListener of login button after getting the String flag value like:
if(flag.equals(landlord)){
Intent intent = new Intent(this,Landlord.class);
startActivity(intent);
}
else{
Intent intent = new Intent(this,Tenant.class);
startActivity(intent);
}
Anyhow you will be querying to verify username & password, at the same time you could also fetch the flag information and store it in locally(reduces the database calls).
Store those data in a map with key as username (Assumption username will be unique) and flag as value.
Map<String,String> mapToRouting = new Map<String,String>();
Now for routing different activities, inside the button click method try like
public static void buttonClickMethod(){
//textFieldUserName is the username of user trying to login
if(isLanlord(textFieldUserName)){
//this means user is Landlord & put code to redirect to corresponding screen
}
else{
//put code to which redirects to tenants screen!
}
}
Method to find whether the user is landlor or not.
public static void isLandlord(String userName){
boolean result = false;
if(mapToRouting.get(userName).equalsIgnorecase("Landlord"))
result = true;
return result;
}
Hope this will be helpful.
I am trying to send ArrayList(VideoUrlArrayList) values inside a for loop to Android Download Manager but i keep getting following error:
error: incompatible types: String cannot be converted to Uri
and pointing to this line:
DownloadManager.Request request = new DownloadManager.Request(VideoUrlArrayList.get(i));
fileName = VideoUrlArrayList.get(i).substring(VideoUrlArrayList.get(i).lastIndexOf("/"));
if i remove the part of code that sends urls to Download Manager the toast displays the arrayList(VideoUrlArrayList) values correctly !
Could you guys help me fix this problem and successfully send values of my ArrayList to Download Manager?(Furthermore, I want to use the original file names from urls stored in VideoUrlArrayList).Thanks
MainAcitivty.java:
public class MainActivity extends AppCompatActivity {
private DownloadManager downloadManager;
private long refid;
private String fileName;
ArrayList<Long> list = new ArrayList<>();
ArrayList<String> VideoUrlArrayList =new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
registerReceiver(onComplete,
new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
TextView btnMultiple = (TextView) findViewById(R.id.multiple);
if(!isStoragePermissionGranted())
{
}
btnMultiple.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
list.clear();
EditText editText1 = (EditText) findViewById(R.id.editText);
String linesArray[] = editText1.getText().toString().split("\n");
for (int i = 0; i < linesArray.length; i++) {
String currLine = linesArray[i];
VideoUrlArrayList.add(currLine);
}
for (int i = 0; i < VideoUrlArrayList.size(); i++) {
//Toast.makeText(getApplicationContext(), "Array Text: " + VideoUrlArrayList.get(i), Toast.LENGTH_LONG).show();
DownloadManager.Request request = new DownloadManager.Request(VideoUrlArrayList.get(i));
fileName = VideoUrlArrayList.get(i).substring(VideoUrlArrayList.get(i).lastIndexOf("/"));
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setAllowedOverRoaming(false);
//Set the title of this download, to be displayed in notifications (if enabled).
request.setTitle("Demo Downloading " + fileName);
//Set a description of this download, to be displayed in notifications (if enabled)
request.setDescription("Downloading " + fileName);
//Set whether this download should be displayed in the system's Downloads UI. True by default.
request.setVisibleInDownloadsUi(true);
//Set the local destination for the downloaded file to a path within the public external storage directory (as returned by getExternalStoragePublicDirectory(String)).
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
refid = downloadManager.enqueue(request);
Log.e("OUTNM", "" + refid);
list.add(refid);
}
}
});
//the rest of code after this
}
Make this line:
DownloadManager.Request request = new DownloadManager.Request(VideoUrlArrayList.get(i));
to:
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(VideoUrlArrayList.get(i)));
DoesnloadManager.Request() accepts Uri not String. So you need to parse it to Uri.
I have a weird problem with showing my custom alert dialog from inside my async task's post execute method. When the program is run, the progress dialog from my pre-execute is first of all dismissed in the post execute before I then display my custom alert dialog which displays parsed JSON data. But the custom alert dialog does not show up at all, after dismissing the progress dialog.
Please, can anyone help with possible reasons why that's happening? Here is the code from my post exec method.
#Override
protected void onPostExecute(String result) {
loginDialog.dismiss();
jsonstring = result;
try {
jsonObject = new JSONObject(jsonstring);
jsonArray = jsonObject.getJSONArray("server_response");
JSONObject JO = jsonArray.getJSONObject(0);
fname = JO.getString("firstname");
lname = JO.getString("lastname");
possessionqty = JO.getString("possessionQty");
email = JO.getString("email");
status = JO.getString("status");
mBuilder = new AlertDialog.Builder(activity);
mView = getLayoutInflater().inflate(R.layout.studentinfo_alertdialog, null);
studentIDheader = (TextView) mView.findViewById(R.id.textView3);
studentfullname = (EditText) mView.findViewById(R.id.editText);
studentpossessionqty = (EditText) mView.findViewById(R.id.editText2);
studentemail = (EditText) mView.findViewById(R.id.editText3);
studentstatus = (EditText) mView.findViewById(R.id.editText4);
studentIDheader.setText(validatedID);
studentfullname.setText("Full Name: " + fname + " " + lname);
studentpossessionqty.setText("Possession Qty: " + possessionqty);
studentemail.setText("Email: " + email);
studentstatus.setText("Status: " + status);
mBuilder.setCancelable(false);
mBuilder.setView(mView);
dialog = mBuilder.create();
dialog.show();
} catch (JSONException e) {
e.printStackTrace();
}
}
This question already has answers here:
How do I pass data between Activities in Android application?
(53 answers)
Closed 5 years ago.
This code below returns json into a textView. How do I pass the data within this textview to another activity?
private void showJSON(String response){
String name="";
String address="";
String vc = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject collegeData = result.getJSONObject(0);
name = collegeData.getString(Config.KEY_NAME);
address = collegeData.getString(Config.KEY_ADDRESS);
vc = collegeData.getString(Config.KEY_VC);
} catch (JSONException e) {
e.printStackTrace();
}
textViewResult.setText("Name:\t"+name+"\nAddress:\t" +address+ "\nVice Chancellor:\t"+ vc);
}
This is the tutorial link I'm following. I know it can be done using intents but I wasn't sure how to use it in this example.
Thanks
String json=textViewResult.getText().toString();
startActivity(new Intent(this,YourActivity.class).putExtra("data",json));
Is this what you want?
Pass String data using putExtra
Intent i = new Intent(youractivity.this, SecondActivity.class);
i.putExtra("name",name);
i.putExtra("address",address);
i.putExtra("vc",vc);
startActivity(i);
In SecondActivity
String name=getIntent().getStringExtra("name");
String address=getIntent().getStringExtra("address");
String vc=getIntent().getStringExtra("vc");
OR
Pass json data from activity
Intent i = new Intent(youractivity.this, SecondActivity.class);
intent.putExtra("jsonObject", jsonObject.toString());
startActivity(i);
In SecondActivity
Intent intent = getIntent();
String jsonString = intent.getStringExtra("jsonObject");
JSONObject jsonObject = new JSONObject(jsonString);
Thank you all for the answers. This has helped me understand how to use intents and I was able to solve my problem with this:
Activity 1
String json= textViewResult.getText().toString();
Intent i = new Intent(Activity1.this, Activity2.class);
i.putExtra("Data",json);
startActivity(i);
Activity 2
Bundle b = getIntent().getExtras();
String json = b.getString("Data");
TextView jData = (TextView) findViewById(R.id.textView1);
jData.setText(json);